如何设计深度优先搜索(DFS)
搜索到位置,进行一个标记,按照上下左右搜索,直到某一个点的深度遍历全都搜索完毕,岛屿数量加1
小象学院给的是使用一个辅助数组进行标记,其实用原先的一个数组也是可以的,遍历中心位之后,如果中心位是1,count++将中心位置为非1的数字就好了,我看网上有置为0的,我们为了和水域也分开比较,我们将遍历过的土地置为1.
我们
如何设计宽度优先搜索(BFS)
宽度搜索需要借助队列记录搜索到的节点
DFS代码
class Solution {
public int numIslands(char[][] grid) {
int x = grid.length;//行
//边界条件
int counts_island=0;
if(grid != null && x>0 ){
int y = grid[0].length;//列
for(int i=0;i<x;i++){
for(int j=0;j<y;j++){
if(grid[i][j]=='1'){
DFS(i,j,grid);
counts_island++;
}
}
}
}
return counts_island;
}
public void DFS(int i, int j, char[][] grid){
//递归结束条件
if(i<0||j<0||i>grid.length-1||j>grid[0].length-1){
return;
}
if(grid[i][j]=='1'){
//中心位置重置
grid[i][j]='2';
//上
DFS(i-1,j,grid);
//下
DFS(i+1,j,grid);
//左
DFS(i,j-1,grid);
//右
DFS(i,j+1,grid);
}
}
}
bfs是从网上找的代码,借助队列
class Solution {
public int numIslands(char[][] grid) {
// corner case
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int count = 0;
int rows = grid.length;
int cols = grid[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == '1') {
count++;
LinkedList<int []> queue = new LinkedList<int []>();
queue.add(new int[]{i, j});
while (!queue.isEmpty()) {
int[] cur = queue.poll();
for (int[] dir : dirs) {
int x = cur[0] + dir[0];
int y = cur[1] + dir[1];
if(x >= 0 && x < rows && y >= 0 && y < cols && grid[x][y] =='1'){
grid[x][y] = '0';
queue.add(new int[]{x, y});
}
}
}
}
}
}
return count;
}
}
其实bfs应该不难,多了一个队列,保存遍历的节点,然后再遍历这些节点能够遍历到的节点
总的来说,还是深度优先遍历好理解啊哈哈,上下左右四个递归就好了我