373. Island Perimeter
You are given a rectangular map grid with rows rows and cols columns, where grid[r][c] is 1 for land and 0 for water. All of the land forms one single island: land cells connect up/down/left/right, the island has no lakes (no water completely enclosed by land), and everything outside the grid counts as water.
Each cell is a 1 × 1 square. Return the perimeter of the island — the total length of its coastline. A side of a land cell counts toward the perimeter exactly when the square across that side is water or lies outside the grid.
Example 1:
Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
Output: 16
Explanation: The seven land cells form a plus-like shape whose outline is 16 unit edges long (traced in the figure).
Example 2:
Input: grid = [[1]]
Output: 4
Explanation: A lone land cell touches water (or the grid border) on all four sides, so its perimeter is 4.
Constraints:
- 1 ≤ rows, cols ≤ 100
- grid[r][c] is 0 or 1
- There is exactly one island, and it contains no lakes.
Hints:
Every land cell starts with 4 units of fence. Which of those units survive into the final perimeter?
A side counts exactly when its neighbor across the side is water or off the grid — so visit each land cell and probe its 4 neighbors.
No traversal needed: perimeter = 4 · (land cells) − 2 · (pairs of land cells that share a side). Count only right and down neighbors so each shared side is counted once.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
Expected output: 16