My c++ DFS Solution


  • 0
    S
    /***************************************************
    ***   author : s2003zy
    ***   weibo  : http://weibo.com/songzy982
    ***************************************************/
    class Solution {
    public:
        void removeIsland(vector< vector<char> > &grid, int i, int j) {
            if (i >= 0 && i < grid.size() && j >=0 && j < grid[0].size() && grid[i][j] == '1') {
                grid[i][j] = '0';
                removeIsland(grid, i + 1, j);
                removeIsland(grid, i - 1, j);
                removeIsland(grid, i, j + 1);
                removeIsland(grid, i, j - 1);
            }
        }
        int numIslands(vector<vector<char>> &grid) {
            int res = 0;
            for (int i = 0; i < grid.size(); i++) {
                for (int j = 0; j < grid[0].size(); j++) {
                    if (grid[i][j] == '1') {
                        res++;
                        removeIsland(grid, i, j);
                    }
                }
            }
            return res;
        }
    };

Log in to reply
 

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