zwkcoding / 100Days-Of-Leetcode

就像电影(500)Days of Summer一样,记录着每一天 Leetcode @itgoyo/500Days-Of-Github
0 stars 0 forks source link

05 Explore00_Stack and DFS_ Number of Islands_Chapter04 #10

Open zwkcoding opened 5 years ago

zwkcoding commented 5 years ago

Keywords: DFS, Recursion Notes:

zwkcoding commented 5 years ago

Problem: Nums of Islands Solution ;

zwkcoding commented 5 years ago

HandCoding Code :)

# Solution use BFS
class Solution {
public:
    int numIslands(vector<vector<char> >& grid)  {
        int m = grid.size();
        int n = m ? grid[0].size() : 0;
        islands = 0;
        offset[] = {0, 1, 0, -1, 0};
        for(int i = 0; i < m; i++)  {
            for(int j = 0; j < n; j++)  {
                if(grid[i][j] == '1')  {
                    islands++;
                    grid[i][j] = '0';
                    queue<pair<int, int> > todo;
                    todo.push({i,j});
                    while(!todo.empty())  {
                        pair<int, int> p = todo.front();
                        todo.pop();
                        for (int k = 0; k < 4; k++)  {
                            int r = p.first + offset[k],;
                            int c = p.second + offset[k+1];
                            if(r >= 0 && r < m && c >= 0 && c < n && grid[r][c] == '1')  {
                                grid[r][c] = '0';
                                todo.push({r,c});
                            }
                        }
                    }

                }
            }
        }
        return islands;
    }

};

# Solution uses DFS
class Solution  {
public:
    int numIslands(vector<vector<char> >& grid)  {
        int m = grid.size(), n = m ? grid[0].size() : 0, islands = 0;
        for(int i = 0; i < m; i++)  {
            for(int j = 0; j < n; j++)  {
                if (grid[i][j] == '1')  {
                    islands++;
                    eraseIslands(grid, i, j);
                }
            }
        }
        return islands;
    }

private:
    void eraseIslands(vector<vector<char> >& grid, int i, int j)  {
        int m = grid.size(), n = grid[0].size();
        if (i < 0 || i == m || j < 0 || j == n || grid[i][j] == '0')  {
            return;
        }
        grid[i][j] = '0';
        eraseIslands(grid, i - 1, j);
        eraseIslands(grid, i + 1, j);
        eraseIslands(grid, i, j - 1);
        eraseIslands(grid, i, j + 1);
    }
};