// 执行用时: 16 ms // 内存消耗: 9.4 MB classSolution { public: vector<vector<char>> g; int m, n; int res = 0; constint dr[4] = {-1, 0, 1, 0}, dc[4] = {0, 1, 0, -1}; intnumIslands(vector<vector<char>>& grid){ g = grid; m = grid.size(), n = grid[0].size();
for (int i = 0; i < m; i ++ ) { for (int j = 0; j < n; j ++) { if (g[i][j] == '1') { dfs(i, j); res ++; } } }
return res; }
voiddfs(int r, int c){ g[r][c] = '0'; for (int i = 0; i < 4; i ++ ) { int ner = r + dr[i], nec = c + dc[i]; if (ner >= 0 && ner < m && nec >= 0 && nec < n && g[ner][nec] == '1') { dfs(ner, nec); } } } };
// 执行用时: 2 ms // 内存消耗: 40.9 MB classSolution{ int[] dr, dc; char[][] g; int m, n; int res = 0; publicintnumIslands(char[][] grid){ g = grid; m = grid.length; n = grid[0].length; dr = newint[] {-1, 0, 1, 0}; dc = newint[] {0, 1, 0, -1};
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (g[i][j] == '1') { res ++; dfs(i, j); } } }
return res; }
privatevoiddfs(int r, int c){ g[r][c] = '0'; for (int d = 0; d < 4; d++) { int ner = r + dr[d], nec = c + dc[d]; if (ner >= 0 && ner < m && nec >= 0 && nec < n && g[ner][nec] == '1') { dfs(ner, nec); } } } }
BFS
在Java语言中,可以使用当前行与列 i, j 和总列数 n 进行hash运算,将结果入队,以代替pair. encode: int hash = i * n + j; decode: int i = hash / n, j = hash % n;
// 执行用时: 16 ms // 内存消耗: 10.2 MB classSolution { public: vector<vector<char>> g; int64_t m, n; constint dr[4] = {-1, 0, 1, 0}, dc[4] = {0, 1, 0, -1}; int res = 0; intnumIslands(vector<vector<char>>& grid){ g = grid; m = g.size(), n = g[0].size();
for (int i = 0; i < m; i++ ) { for (int j = 0; j < n; j++) { if (g[i][j] == '1') { res++; bfs(i, j); } } }
return res; }
voidbfs(int i, int j){ queue<pair<int, int>> q; q.push({i, j}); g[i][j] = '0'; for (; q.size();) { int r = q.front().first, c = q.front().second; q.pop();
for (int d = 0; d < 4; d ++) { int ner = r + dr[d], nec = c + dc[d]; if (ner >= 0 && ner < m && nec >= 0 && nec < n && g[ner][nec] == '1') { q.push({ner, nec}); g[ner][nec] = '0'; } } } }
// 执行用时: 3 ms // 内存消耗: 40.9 MB classSolution{ int[] dr, dc; char[][] g; int m, n; int res = 0; publicintnumIslands(char[][] grid){ g = grid; dr = newint[] {-1, 0, 1, 0}; dc = newint[] {0, 1, 0, -1}; m = g.length; n = g[0].length;
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (g[i][j] == '1') { res++; bfs(i, j); } } }
return res; }
privatevoidbfs(int i, int j){ Queue<Integer> q = new LinkedList<>(); q.add(i * n + j); g[i][j] = '0';
for (; q.size() > 0;) { int hash = q.remove(); int r = hash / n, c = hash % n; for (int d = 0; d < 4; d++) { int ner = r + dr[d], nec = c + dc[d]; if (ner >= 0 && ner < m && nec >= 0 && nec < n && g[ner][nec] == '1') { g[ner][nec] = '0'; q.add(ner * n + nec); } } } } }