Leetcode 200 岛屿的数量:
DFS利用函数调用栈保证了检索顺序,
BFS则需要自己建立队列,把待检索对象按规则入队。
class Solution { // DFS解法,8ms/10.7MB,99.7% / 92%public: /** * row,col: 坐标,以0开始. * 用row和col,而不是x,y. 否则容易写成grid[x][y],顺序不对!! */ void dfs_set_zero(vector>& grid, int row, int col) { int n_rows = grid.size(); if (!n_rows) return; int n_cols = grid[0].size(); if (!n_cols) return; if (row<0 || row>=n_rows || col<0 || col>=n_cols) return; if (grid[row][col] == '1') { grid[row][col] = '0'; dfs_set_zero(grid, row-1, col); dfs_set_zero(grid, row+1, col); dfs_set_zero(grid, row, col-1); dfs_set_zero(grid, row, col+1); } } int numIslands(vector >& grid) { int result = 0; for (int i=0; i
class Solution { // BFS解法,12ms/11MB, 96.9% / 69.4%public: queue> q; void bfs_set_zero(vector >& grid) { int n_rows = grid.size(); if(!n_rows) return; int n_cols = grid[0].size(); if(!n_cols) return; while (!q.empty()) { auto pos = q.front(); q.pop(); //if (grid[pos.first][pos.second] == '1') { grid[pos.first][pos.second] = '0'; if (pos.first-1>=0 && grid[pos.first-1][pos.second] == '1') q.emplace(pos.first-1,pos.second); if (pos.first+1 =0 && grid[pos.first][pos.second-1] == '1') q.emplace(pos.first,pos.second-1); if (pos.second+1 >& grid) { int result = 0; for (int i=0; i