1.什么是bfs算法
这个博主讲的很详细,链接放在下面了
https://blog.youkuaiyun.com/weixin_72060925/article/details/128145585?spm=1001.2014.3001.5506
2.bfs算法为什么可以解决最短路径问题
因为bfs算法是分层遍历,从起始结点开始,到目标结点,层数最少的就是最短路径,又因为我们规定了访问过的结点就不能被访问,所以又确定了最短路径唯一,那么我们记录结果的数组中一定是最短路径的过程
3.题目

4.代码实现
class pair{
int x;
int y;
public pair(int x,int y)
{
this.x = x;
this.y = y;
}
}
public class BFS {
public static void bfs()
{
Queue<pair> queue = new LinkedList<>();
queue.add(new pair(0, 0));//添加元素
mark[0][0] = "";//赋空
while(!queue.isEmpty())//如果队列不为空
{
pair top = queue.poll();//队头元素出队
for(int i = 0;i<4;i++)//遍历上下左右四个方向
{
int nex = top.x+dx[i];
int ney = top.y+dy[i];
if(nex >= 0 && nex < n && ney >= 0 && ney<m && mark[nex][ney].equals("") && map[nex][ney]=='0')
{
mark[nex][ney] = mark[top.x][top.y] + str[i];
queue.add(new pair(nex,ney));
}
}
}
System.out.println(mark[n-1][m-1]);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
m = scanner.nextInt();
String s = scanner.nextLine();
for(int i = 0;i<n;i++)
map[i] = scanner.nextLine().toCharArray();
for (int i = 0; i < n; i++) {
for(int j = 0;j<m;j++){
mark[i][j] = "";
}
}
bfs();
}
public static final int N = 100;
public static int n,m;//地图的行列
public static char[][] map = new char[N][N];//地图
public static String[][] mark = new String[N][N];//如果mark[i][j]为null那就没有走过该点,还可以存储信息
public static int[] dx = {1,0,0,-1};
public static int[] dy = {0,-1,1,0};
public static String[] str = {"D","L","R","U"};//下,左,右,上
}
1188



被折叠的 条评论
为什么被折叠?



