Skip to content

Instantly share code, notes, and snippets.

@pascaljp
Created November 17, 2019 19:11
Show Gist options
  • Save pascaljp/20d6c923fbb871e25d6ab94c1dc5d741 to your computer and use it in GitHub Desktop.
Save pascaljp/20d6c923fbb871e25d6ab94c1dc5d741 to your computer and use it in GitHub Desktop.
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if (grid.empty() || grid[0].empty()) {
return 0;
}
vector<vector<bool>> checked(grid.size(), vector<bool>(grid[0].size()));
int islands = 0;
for (int y = 0; y < grid.size(); y++) {
for (int x = 0; x < grid[0].size(); x++) {
if (findNewIsland(grid, &checked, x, y)) {
islands++;
}
}
}
return islands;
}
bool findNewIsland(const vector<vector<char>>& grid,
vector<vector<bool>>* checked, int x, int y) {
if (grid[y][x] == '0' || (*checked)[y][x]) {
return false;
}
(*checked)[y][x] = true;
if (y < grid.size() - 1 && grid[y+1][x] == '1')
findNewIsland(grid, checked, x, y + 1);
if (y > 0 && grid[y-1][x] == '1')
findNewIsland(grid, checked, x, y - 1);
if (x < grid[0].size() - 1 && grid[y][x+1] == '1')
findNewIsland(grid, checked, x + 1, y);
if (x > 0 && grid[y][x-1] == '1')
findNewIsland(grid, checked, x - 1, y);
return true;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment