Created
October 3, 2019 13:03
-
-
Save vitkarpov/0b12ba6b78ec7b77b55034098c32c872 to your computer and use it in GitHub Desktop.
200. Number of Islands (https://leetcode.com/problems/number-of-islands/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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