simple C++ solution...

  • 0

    just checking (x+1,y) , (x-1,y), (x,y+1) and (x,y-1) from each island (x,y). If the range is invalid for the new location, we add one to the perimeter as we are in the surrounding/corner.

    In case the next location we're checking is valid & isn't land, we add another to perimeter.

    int islandPerimeter(vector<vector<int>>& grid) {
            int row = grid.size();
            int col = grid[0].size();
            int perimeter = 0;
            for (int i=0;i<row;i++) {
                for (int j=0;j<col;j++) {
                    if (grid[i][j] == 1) {
                        check(grid, perimeter, i+1, j, row, col);
                        check(grid, perimeter, i-1, j, row, col);
                        check(grid, perimeter, i, j+1, row, col);
                        check(grid, perimeter, i, j-1, row, col);
            return perimeter;
        void check(vector<vector<int>>&grid, int& perimeter, int i, int j, int row, int col) {
            if (i<0 || j<0 || i == row || j == col || !grid[i][j]) {

Log in to reply

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