岛屿数量(力扣)
**********题目链接
BFS解法 ???时间超限???
class Solution {
public:
int numIslands( vector<vector<char>>& grid ) {
int m = grid.size();
int n = grid[0].size();
if( n == 0 || m == 0 ) {
return 0;
}
int count = 0;
for( int i = 0; i < m; i++ ) {
for( int j = 0; j < n; j++ ) {
if( grid[i][j] == '1' ) {
count++;
Search( grid, i, j, m, n );
}
}
}
return count;
}
void Search( vector<vector<char>>& grid, int i, int j, int m, int n ) {
queue<int>q;
q.push( i * n + j );
while( !q.empty() ) {
int front = q.front();
q.pop();
int x = front / n;
int y = front % n;
grid[x][y] = '0';
//up
if( x - 1 >= 0 && grid[x - 1][y] == '1' ) {
q.push( ( x - 1 )*n + y );
}
//down
if( x + 1 < m && grid[x + 1][y] == '1' ) {
q.push( ( x + 1 )*n + y );
}
//left
if( y - 1 >= 0 && grid[x][y - 1] == '1' ) {
q.push( x * n + y - 1 );
}
//right
if( y + 1 < n && grid[x][y + 1] == '1' ) {
q.push( x * n + y + 1 );
}
}
}
};
DFS解法 这个过了
class Solution {
public:
int numIslands( vector<vector<char>>& grid ) {
int m = grid.size();
int n = grid[0].size();
int count = 0;
for( int i = 0; i < m; i++ ) {
for( int j = 0; j < n; j++ ) {
if( grid[i][j] == '1' ) {
count++;
Search( grid, i, j, m, n );
}
}
}
return count;
}
void Search( vector<vector<char>>& grid, int i, int j, int m, int n ) {
grid[i][j] = '0';
//up
if( ( i - 1 >= 0 ) && grid[i - 1][j] == '1' ) {
Search( grid, i - 1, j, m, n );
}
//down
if( ( i + 1 < m ) && grid[i + 1][j] == '1' ) {
Search( grid, i + 1, j, m, n );
}
//left
if( ( j - 1 >= 0 ) && grid[i][j - 1] == '1' ) {
Search( grid, i, j - 1, m, n );
}
//right
if( ( j + 1 < n ) && grid[i][j + 1] == '1' ) {
Search( grid, i, j + 1, m, n );
}
}
};