463. Island Perimeter (actually counting

T: O(mn)

S: O(1)

class Solution {
    public int islandPerimeter(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int result = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 0) {
                    continue;
                }
                if (i - 1 == -1 || grid[i-1][j] == 0) { // up
                    result++;
                }
                if (i + 1 == m || grid[i+1][j] == 0) { // down
                    result++;
                }

                if (j - 1 == -1 || grid[i][j-1] == 0) { // left
                    result++;
                }
                if (j + 1 == n || grid[i][j+1] == 0) { // right
                    result++;
                }
            }
        }
        return result;
    }
}

/***
 
    j 0 1 2
  i
  0 0 1 0 0 
  1 0 1 0 0
  2

 */

Last updated