Leetcode 200.岛屿的数量 - DFSBFS
Posted dylanchu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 200.岛屿的数量 - DFSBFS相关的知识,希望对你有一定的参考价值。
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<vector<char>>& 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<vector<char>>& grid)
int result = 0;
for (int i=0; i<grid.size(); ++i)
for (int j=0; j<grid[0].size(); ++j)
if (grid[i][j] == '1')
result++;
dfs_set_zero(grid, i, j);
return result;
;
class Solution // BFS解法,12ms/11MB, 96.9% / 69.4%
public:
queue<pair<int,int>> q;
void bfs_set_zero(vector<vector<char>>& 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<n_rows && grid[pos.first+1][pos.second] == '1')
q.emplace(pos.first+1,pos.second);
if (pos.second-1>=0 && grid[pos.first][pos.second-1] == '1')
q.emplace(pos.first,pos.second-1);
if (pos.second+1<n_cols && grid[pos.first][pos.second+1] == '1')
q.emplace(pos.first,pos.second+1);
int numIslands(vector<vector<char>>& grid)
int result = 0;
for (int i=0; i<grid.size(); i++)
for (int j=0; j<grid[0].size(); j++)
if (grid[i][j] == '1')
result++;
//q.push(make_pair(i,j));
q.emplace(i,j); // 使用emplace而非push,constructed in-place
bfs_set_zero(grid);
return result;
;
以上是关于Leetcode 200.岛屿的数量 - DFSBFS的主要内容,如果未能解决你的问题,请参考以下文章