# Lintcode解题笔记 - 岛屿的个数

0代表海，1代表岛，如果两个1相邻，那么这两个1属于同一个岛。我们只考虑上下左右为相邻。

[
[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[0, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 1]
]

class Solution {
public:
/**
* @param grid a boolean 2D matrix
* @return an integer
*/
int numIslands(vector<vector<bool>>& grid) {
int row = grid.size();
if(row < 1)
return 0;
int column = grid[0].size();
vector<int> tmp(column, 0);
vector<vector<int>> visited(row, tmp);
//int visited[row][column] = 0;
//vector<vector<bool>> visited = grid;
int result = 0;
for(int i = 0; i < row; i++){
for(int j = 0; j < column; j++ ){
if(grid[i][j] == true && visited[i][j] != 1){
floodRush(i,j, visited, grid);
result++;
}

}
}
return result;

}

void floodRush(int row, int column, vector<vector<int>> & visited, vector<vector<bool>> grid){
if(row < 0 || column < 0 || row >= grid.size() || column >= grid[0].size() ){
return;
}
if(visited[row][column] == 1)
return;
if(grid[row][column] == true){
visited[row][column] = 1;
floodRush(row-1, column, visited, grid);
floodRush(row+1, column, visited, grid);
floodRush(row, column-1, visited, grid);
floodRush(row, column+1, visited, grid);
}else{
return;
}

}

};

• 本文已收录于以下专栏：

举报原因： 您举报文章：Lintcode解题笔记 - 岛屿的个数 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)