原文链接: http://www.lintcode.com/zh-cn/problem/number-of-islands/
给一个01矩阵,求不同的岛屿的个数。
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]
]
中有 3 个岛.
思路一:
使用一个辅助数组,visited[][],大小和原数组gird相同,遍历grid数组,如果对应元素grid[i][j]在visited中也没有访问,则将visited[i][j]设置为1, 然后遍历visited[i][j]的上下左右4个元素。
使用辅助的floodRush函数,该函数用于判断/设定visited[i][j]的值,然后递归遍历visited[i][j]上下左右4个元素
该解法在第8个case时候,遇到超时问题,可能是时间复杂度过高
class Solution {
public:
/**
* @param grid a boolean 2D matrix
* @return an integer
*/
int numIslands(vector<vector<bool>>& grid) {
// Write your code here
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;
}
}
};
几个总结,传递以为数组时候,可以使用void A(int a[]),但传递二维数组的时候,需要使用A(int a[][xxx]),来传递。因为编译器需要之后二维数组中某一维度的深度。 参见http://www.cplusplus.com/doc/tutorial/arrays/