1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
| #include <iostream> #include <vector> #include <queue> using namespace std;
class Solution { public: int numIslands(vector<vector<char>>& grid) { int rows = grid.size(), cols = grid[0].size(); int res = 0;
for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (grid[i][j] == '1') { res++; dfs(grid, i, j); } } }
return res; }
void dfs(vector<vector<char>>& grid, int x, int y) { grid[x][y] = '0'; for (int i = 0; i < 4; i++) { int new_x = x + dx[i], new_y = y + dy[i]; if (new_x >= 0 && new_x < grid.size() && new_y >= 0 && new_y < grid[0].size() && grid[new_x][new_y] == '1') { dfs(grid, new_x, new_y); } } }
private: int dx[4] = {-1, 0, 1, 0}; int dy[4] = {0, 1, 0, -1}; };
class Solution_1 { public: int numIslands(vector<vector<char>>& grid) { int rows = grid.size(), cols = grid[0].size(); int res = 0;
for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (grid[i][j] == '1') { res++; bfs(grid, i, j); } } }
return res; }
void bfs(vector<vector<char>>& grid, int x, int y) { int rows = grid.size(), cols = grid[0].size(); queue<int> q; q.push(x*cols + y); grid[x][y] = '0';
while (!q.empty()) { int cur = q.front(); q.pop(); int cur_x = cur / cols, cur_y = cur % cols; for (int i = 0; i < 4; i++) { int new_x = cur_x + dx[i], new_y = cur_y + dy[i]; if (new_x >= 0 && new_x < rows && new_y >= 0 && new_y < cols && grid[new_x][new_y] == '1') { q.push(new_x* cols + new_y); grid[new_x][new_y] = '0'; } } } }
private: int dx[4] = {-1, 0, 1, 0}; int dy[4] = {0, 1, 0, -1}; };
void printArray(const vector<vector<char>>& nums) { cout << "[\n"; for (size_t i = 0; i < nums.size(); i++) { cout << "["; for (size_t j = 0; j < nums[i].size(); j++) { cout << "\"" << nums[i][j] << "\""; if (j != nums[i].size() - 1) cout << ","; } cout << "]"; if (i != nums.size() - 1) cout << ","; cout << "\n"; } cout << "]" << endl; }
int main() { Solution solution; vector<vector<vector<char>>> grid_cases = { { {'1','1','1','1','0'}, {'1','1','0','1','0'}, {'1','1','0','0','0'}, {'0','0','0','0','0'} }, { {'1','1','0','0','0'}, {'1','1','0','0','0'}, {'0','0','1','0','0'}, {'0','0','0','1','1'} }, };
for (int i = 0; i < grid_cases.size(); i++) { auto& grid = grid_cases[i]; cout << "Input: grid = "; printArray(grid);
int result = solution.numIslands(grid); cout << "Output: " << result << endl; cout << "----------------" << endl; }
return 0; }
|