题目
给一个01矩阵,1代表是陆地,0代表海洋, 如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。
岛屿: 相邻陆地可以组成一个岛屿(相邻:上下左右) 判断岛屿个数。
例如:
输入
[
[1,1,0,0,0],
[0,1,0,1,1],
[0,0,0,1,1],
[0,0,0,0,0],
[0,0,1,1,1]
]
对应的输出为3
思路
遍历每一个点,找到为1的点时候侵蚀它周围的陆地,这个侵蚀过程可以用栈来模拟。
代码
python代码
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 判断岛屿数量
# @param grid char字符型二维数组
# @return int整型
#
class Solution:
def solve(self , grid: List[List[str]]) -> int:
# write code here
directions = [-1, 0, 1, 0, -1]
num_island = 0
h = len(grid)
for i in range(h):
w = len(grid[i]) # 这样比较合理一点,万一陆地和海洋不是一个矩形
for j in range(w):
if(grid[i][j]=="1"):
num_island += 1
stack_tmp = []
stack_tmp.append((i, j))
while(len(stack_tmp)):
ix, iy = stack_tmp.pop()
grid[ix][iy] = "0"
for off in range(4):
nx = ix + directions[off]
ny = iy + directions[off+1]
if((0<=nx<h) and (0<=ny<w) and (grid[nx][ny]=="1")):
stack_tmp.append((nx, ny))
return num_island
c++代码:
class Solution {
public:
/**
* 判断岛屿数量
* @param grid char字符型vector<vector<>>
* @return int整型
*/
int solve(vector<vector<char> >& grid) {
// write code here
//采用栈来存储岛屿
int w = grid[0].size();
int h = grid.size();
int land_num = 0;
vector<int> directions = {-1, 0, 1, 0, -1};
for(int i=0; i<h; i++){
for(int j=0; j<w; j++){
if((int)grid[i][j]-48==1){
land_num++;
stack<pair<int, int>> storage;
storage.push(pair<int,int>(i, j));
while(!storage.empty()){
int ix = storage.top().first;
int iy = storage.top().second;
grid[ix][iy]='0';
storage.pop();
for(int di=0; di<4; di++){
int nx = ix+directions[di];
int ny = iy+directions[di+1];
if(0<=nx && nx<h && 0<=ny && ny<w && (int)grid[nx][ny]-48==1){
storage.push(pair<int, int>(nx, ny));
}
}
}
}
}
}
return land_num;
}
};