Determine the perimeter of Island using C++ DFS


  • 0
    T

    '''
    class Solution {
    public:
    int islandPerimeter(vector<vector<int>>& grid) {
    int row = grid.size();
    int col = grid[0].size();
    if (grid.empty()) return 0;
    int sum = 0, sr = 0, sc = 0;
    for (int i =0; i < row; i ++) {
    for (int j =0; j < col; j++) {
    if (grid[i][j] == 1) {
    sr = i;
    sc = j;
    break;
    }
    }
    }

        sum += addPerimeter(grid, sr, sc, row, col);
        return sum;
    }
    
    int addPerimeter (vector<vector<int>>&grid, int i , int j, int row, int col) {
        if (i < 0 || i >= row || j < 0 || j >= col || grid[i][j] == 0)
            return 1;
        if (grid[i][j] == -1)
            return 0;
        
        grid[i][j] = -1;
        
        return addPerimeter(grid, i+1, j, row, col) +
            addPerimeter(grid, i-1, j, row, col) +
            addPerimeter(grid, i, j+1, row, col) +
            addPerimeter(grid, i, j-1, row, col);     
        
    }
    

    };
    '''


Log in to reply
 

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