package ENP.Gird.Gird_path_up;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
//测试:
// 带炸弹:可踩,同时炸平上下左右四周墙
// 带陷阱:可踩,耗费三步
// BFS
public class Gird_path_Bomb {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int n = sc.nextInt();//n行
int m = sc.nextInt();//m列
int[] begin = new int[2];//起点
int[] end = new int[2]; //终点
//地图
int[][] map = new int[n][m];
for(int i = 0; i < n; i++){
for(int j= 0; j < m; j++){
map[i][j] = sc.nextInt();
if(map[i][j] == 2) begin = new int[]{i, j};
if(map[i][j] == 3) end = new int[]{i, j};
}
}
System.out.println(bfs(map,begin,end));
}
}
public static int bfs(int[][] map, int[] begin, int[] end) {
//移动的四个方向
int[] dx = {1, 0, -1, 0};
int[] dy = {0, 1, 0, -1};
//用来储存距离到起始点最短路径的二维数组
int[][] d = new int [map.length][map[0].length];
//储存未进行处理的点
Queue<int[]> que = new LinkedList<int[]>();
boolean[][] visit = new boolean[map.length][map[0].length]; //boolean默认为false
//将所有的位置都初始化为最大,即记录没有遍历的节点,剩下的路径选择只在其中找,与visit数组作用相同。注意Arrays.fill(arr, val)函数只能用于填充一维数组
// for(int i = 0; i < d.length; i++) {
// for(int j = 0; j < d[0].length; j++) {
// d[i][j] = Integer.MAX_VALUE;
// }
// }
//将起始点放入队列
que.offer(begin);
//将起始点最短路径设为0
d[ begin[0] ][ begin[1] ] = 0;
//一直循环直到队列为空
while(!que.isEmpty()) {
// for(int i=que.size(); i>0; i--){ //层次遍历,求最短路径条数添加层序遍历即可
//取出队列中最前端的点
int[] current = que.poll();
//如果是终点则结束
if(current[0] == end[0] && current[1] == end[1]) break;
//四个方向循环
for(int i = 0; i < 4; i++) {
//试探
int nx = current[0] + dx[i];
int ny = current[1] + dy[i];
//判断是否可以走
if(nx >= 0 && nx < map.length && ny >= 0 && ny < map[0].length && map[nx][ny] != 1 && visit[nx][ny] == false) {
if(map[nx][ny] == 4) {
d[nx][ny] = d[current[0]][current[1]] + 2;
}
if(map[nx][ny] == 6){
if(nx + 1>= 0 && nx + 1< map.length && ny >= 0 && ny < map[0].length) map[nx + 1][ny] = 0;
if(nx - 1>= 0 && nx - 1< map.length && ny >= 0 && ny < map[0].length) map[nx - 1][ny] = 0;
if(nx >= 0 && nx < map.length && ny + 1 >= 0 && ny + 1 < map[0].length) map[nx][ny + 1] = 0;
if(nx >= 0 && nx < map.length && ny - 1 >= 0 && ny - 1 < map[0].length) map[nx][ny - 1] = 0;
}
//如果可以走,则将该点的距离加1
d[nx][ny] = d[current[0]][current[1]] + 1;
visit[nx][ny] = true;
//并将该点放入队列等待下次处理
int[] c = {nx, ny};
que.offer(c);
}
}
}
return d[end[0]][end[1]];
}
}
LeetCode刷题-网格路径问题-bomb
最新推荐文章于 2024-10-05 12:29:44 发布
这篇博客主要介绍了如何使用BFS(广度优先搜索)算法解决一个特殊的网格路径问题。在这个问题中,网格中的某些格子可能带有炸弹(可炸平周围墙)或陷阱(消耗额外步骤)。程序首先读取网格的大小和起点、终点的位置,然后通过BFS寻找从起点到终点的最短路径。在遍历过程中,遇到炸弹会更新周围格子的状态,遇到陷阱会增加步数。最终,程序返回到达终点的最短步数。
摘要由CSDN通过智能技术生成