My java solution to solve. Easy to understand.


  • 0
    C

    public class Solution {
    public int islandPerimeter(int[][] grid) {
    if (grid == null || grid.length == 0) {
    return 0;
    }
    int m = grid.length;
    int n = grid[0].length;
    int count = 0;
    for (int i = 0; i < m; ++i) {
    for (int j = 0; j < n; ++j) {
    if (grid[i][j] == 1) {
    if (i - 1 < 0 || i - 1 >= 0 && grid[i - 1][j] == 0) {
    count++;
    }
    if (i + 1 >= m || i + 1 < m && grid[i + 1][j] == 0) {
    count++;
    }
    if (j - 1 < 0 || j - 1 >= 0 && grid[i][j - 1] == 0) {
    count++;
    }
    if (j + 1 >= n || j + 1 < n && grid[i][j + 1] == 0) {
    count++;
    }
    }
    }
    }
    return count;
    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.