1.题目描述
1.1笔者分析
以本题为例对深度优先搜索算法和广度优先搜索算法进行一个小小的总结。结合下列代码进行说明。
public class Test {
private int m;
private int n;
private int[][] pos={{-1,0},{1,0},{0,1},{0,-1}};
private Queue<List<Integer>> queue=new LinkedList<>();
public int shortBridge(int[][] A){
m=A.length;
n=A[0].length;//深度优先搜索
boolean isFindFirst=false;
for(int i=0;i<m;i++){//通过两个for循环对整张表的所有结点进行遍历,遍历到一个结点时,对该点进行深度优先搜索
for(int j=0;j<n;j++){
if(A[i][j]==1){
dfs(A,i,j);//深度优先搜索的原理是,从指定点出发,向四周扩散,递归调用该方法,到达边界或者题目设定条件时返回。递归过程中
isFindFirst=true;//每次遍历到其它点时,都要将其标志为已访问,防止死循环。当以该点为出发点遍历完周围所有合法点后,结束。
break;//对两层for循环中的其它点重复上述操作。
}
}
if(isFindFirst){
break;
}
}
int step=0;
while(!queue.isEmpty()){//广度优先搜索
int size=queue.size();//将表中所有满足条件的点入队列,为第一批点。对该第一批点进行遍历,遍历到某一点时,弹出该点,并将其周围符合条件的点入队,为第二批点。第一批点遍历完之后,原来的第二批点为新的第一批,重复上述操作。
while(size-->0){
List<Integer> list=queue.poll();
for(int[] idx:pos){
int newX=list.get(0)+idx[0];
int newY=list.get(0)+idx[1];
if(!isInArea(newX,newY)||A[newX][newY]!=1){
continue;
}
if(A[newX][newY]==1){
return step;
}
A[newX][newY]=2;
queue.offer(Arrays.asList(newX,newY));
}
}
++step;
}
return step;
}
private void dfs(int[][] A,int i,int j){
queue.offer(Arrays.asList(i,j));
A[i][j]=2;
for(int[] idx:pos) {
int newX = i + idx[0];
int newY = j + idx[1];
if (!isInArea(newX, newY) || A[newX][newY]!=1) {
continue;
}
dfs(A,newX,newY);
}
}
private boolean isInArea(int i,int j){
return i >= 0 && i < m && j >= 0 && j < n;
}
}