YunheWang0813
9/9/2019 - 5:52 PM

0200. Number of Islands

struct Coord {
    int x;
    int y;
    Coord(int tmp_x, int tmp_y): x(tmp_x), y(tmp_y) {}
};

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if (grid.empty() || grid.size() == 0 || grid[0].empty() || grid[0].size() == 0) return 0;
        res = 0;
        four_ways = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        
        for (int i = 0; i < grid.size(); i++) {
            for (int j = 0; j < grid[0].size(); j++) {
                if (grid[i][j] == '1') {
                    Coord c(i, j);
                    bfs(grid, c);
                    res++;  
                }
            }
        }
        return res;
    }
    
private:
    int res;
    vector<vector<int>> four_ways;
    void bfs(vector<vector<char>>& grid, Coord& c) {
        queue<Coord> Q;
        Q.push(c);
        grid[c.x][c.y] = '0';
        while(!Q.empty()) {
            Coord cur_c = Q.front(); Q.pop();
            for (int i = 0; i < 4; i++) {
                Coord new_c(cur_c.x + four_ways[i][0], cur_c.y + four_ways[i][1]);
                if (is_valid(grid, new_c)) {
                    Q.push(new_c);
                    grid[new_c.x][new_c.y] = '0';
                }
            }
        }
    }
    bool is_valid(vector<vector<char>>& grid, Coord& c) {
        if (c.x < 0 || c.x >= grid.size() || c.y < 0 || c.y >= grid[0].size() || grid[c.x][c.y] == '0') {
            return false;
        }
        return true;
    }
};