Skip to content

Instantly share code, notes, and snippets.

@vitkarpov
Created October 3, 2019 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitkarpov/0b12ba6b78ec7b77b55034098c32c872 to your computer and use it in GitHub Desktop.
Save vitkarpov/0b12ba6b78ec7b77b55034098c32c872 to your computer and use it in GitHub Desktop.
class Solution {
private:
void eraseIsland(vector<vector<char>>& grid, int x, int y) {
if (grid[y][x] == '0') {
return;
}
grid[y][x] = '0';
if (y > 0) eraseIsland(grid, x, y - 1);
if (y < grid.size() - 1) eraseIsland(grid, x, y + 1);
if (x > 0) eraseIsland(grid, x - 1, y);
if (x < grid[0].size() - 1) eraseIsland(grid, x + 1, y);
}
public:
int numIslands(vector<vector<char>>& grid) {
int islands = 0;
for (int y = 0; y < grid.size(); y++) {
for (int x = 0; x < grid[0].size(); x++) {
if (grid[y][x] == '1') {
eraseIsland(grid, x, y);
islands++;
}
}
}
return islands;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment