Untitled
Never
#include <iostream> #include <vector> class Solution { public: int numIslands(std::vector<std::vector<char>>& grid) { int numIslands = 0; for (int i = 0; i < grid.size(); ++i) { for (int j = 0; j < grid[i].size(); ++j) { if (grid[i][j] == '1') { ++numIslands; dfs(grid, i, j); } } } return numIslands; } private: void dfs(std::vector<std::vector<char>>& grid, int row, int col) { if (row < 0 || row >= grid.size() || col < 0 || col >= grid[0].size() || grid[row][col] == '0') { return; } grid[row][col] = '0'; // Mark as visited dfs(grid, row - 1, col); dfs(grid, row + 1, col); dfs(grid, row, col - 1); dfs(grid, row, col + 1); } }; int main() { std::vector<std::vector<char>> grid = { {'1', '1', '0', '0', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'} }; Solution solution; int islands = solution.numIslands(grid); std::cout << "Number of islands: " << islands << std::endl; return 0; }
Raw Text
-
Breaking news - Update 1 - 11/29/2023 19:28:02
8 min ago
-
Breaking news - Update 1 - 11/29/2023 19:21:26
15 min ago
-
asdas
PHP | 27 min ago
-
sdgsdgsdg
36 min ago
-
grswgr
39 min ago
-
dfawd
40 min ago
-
Breaking news - Update 1 - 11/29/2023 18:50:22
46 min ago
-
Untitled
1 hour ago
-
Untitled
1 hour ago
-
fghfdgh fghdffgh fg
1 hour ago