1. 网格路径问题分类
网格路径问题:从网格中某个点到另一点的最小耗费:
- 若从相邻点之间的耗费相同:使用BFS
- 若相邻点之间的耗费不同:使用DFS
2.解法
2.1 若从相邻点之间的耗费相同:使用BFS
例题:
//测试
//5 5 网格数
//0 1 起点
//3 3 终点
//0 0 0 0 0 网格情况:有障碍物设置坐标值等于1,无障碍物设为0
//0 0 0 0 0
//0 0 0 1 0
//0 0 0 0 0
//0 0 0 0 0
//网格最短路径问题:障碍物不能移除
// BFS
class Gird_path {
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 x1 = sc.nextInt();
int y1 = sc.nextInt();
int[] begin = {x1,y1};//起点
int x2 = sc.nextInt();
int y2 = sc.nextInt();
int[] end = {x2,y2}; //终点
//地图
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();
}
}
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) {
//如果可以走,则将该点的距离加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]];
}
}
2.2 若相邻点之间的耗费不同:使用DFS
待完善