Created
May 8, 2024 14:51
-
-
Save lsem/8ddd9088b3335b423e8dad30a0aad46b to your computer and use it in GitHub Desktop.
number_of_islands.cpp
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 { | |
public: | |
bool flood_fill_nonrecursive(vector<vector<char>>& grid, int px, int py) { | |
struct frame { | |
int x, y; | |
}; | |
vector<frame> stack; | |
stack.emplace_back(frame{px,py}); | |
bool flooded_island = false; | |
while (!stack.empty()) { | |
auto [x, y] = stack.back(); | |
stack.resize(stack.size()-1); | |
if (x < 0 || x >= grid.size()) { | |
continue; | |
} | |
if (y < 0 || y >= grid[x].size()) { | |
continue; | |
} | |
if (grid[x][y] == '1') { | |
flooded_island = true; | |
grid[x][y] = 'x'; | |
stack.emplace_back(frame{x, y - 1}); | |
stack.emplace_back(frame{x, y + 1}); | |
stack.emplace_back(frame{x + 1, y}); | |
stack.emplace_back(frame{x - 1, y}); | |
} | |
} | |
return flooded_island; | |
} | |
void flood_fill(vector<vector<char>>& grid, int x, int y, char c) { | |
if (x < 0 || x >= grid.size()) { | |
return; | |
} | |
if (y < 0 || y >= grid[x].size()) { | |
return; | |
} | |
if (grid[x][y] == '1') { | |
if (c == ' ') { | |
c = next_char(); | |
} | |
grid[x][y] = c; | |
flood_fill(grid, x, y - 1, c); | |
flood_fill(grid, x, y + 1, c); | |
flood_fill(grid, x + 1, y, c); | |
flood_fill(grid, x - 1, y, c); | |
} | |
} | |
int numIslands(vector<vector<char>>& grid) { | |
int islands = 0; | |
for (size_t i = 0; i < grid.size(); ++i) { | |
for (size_t j = 0; j < grid[i].size(); ++j) { | |
if (grid[i][j] == '1') { | |
if (flood_fill_nonrecursive(grid, i,j)) { | |
islands++; | |
} | |
} | |
} | |
} | |
return islands; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment