Island Perimeter

Easy GraphMatrix

Problem

Given a grid with exactly one 4-connected island, return its perimeter.

Example 1 Input: [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]] Output: 16

Constraints

Approach — Graphs

This is a Graphs problem. The idea: explore the graph with BFS or DFS, marking nodes visited so you never process one twice. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(V + E) time.

Solution code

Python

class Solution:
    def islandPerimeter(self, grid):
        rows, cols = len(grid), len(grid[0])
        per = 0
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == 1:
                    per += 4
                    if r > 0 and grid[r - 1][c] == 1:
                        per -= 2
                    if c > 0 and grid[r][c - 1] == 1:
                        per -= 2
        return per

Java

class Solution {
    public int islandPerimeter(int[][] grid) {
        int perimeter = 0;
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[0].length; c++) {
                if (grid[r][c] == 1) {
                    perimeter += 4;
                    if (r > 0 && grid[r - 1][c] == 1) {
                        perimeter -= 2;
                    }
                    if (c > 0 && grid[r][c - 1] == 1) {
                        perimeter -= 2;
                    }
                }
            }
        }
        return perimeter;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Island Perimeter interactively → ← All solutions