第二题,两百分,回溯问题,形似岛屿的数量,多加个回撤。
题目描述
有一张m*n的地图,地图描述了起点和终点的位置,也描述了两点间分布的高山湖泊,高山湖泊挡住去路,需要绕道行走,请问从起点到终点的最短路径有几条,距离是多少?
注意:走动路线只能上下左右,不能斜着走。
输入描述
假设是5*5的地图,那么四个角的坐标表示为(0,0),(0,4) ,(4,4) ,(4,0);
起点是(0,1),重点是(3,3)
高山湖泊的个数:1
高山湖泊的位置 (2,2)
输入表示:
5 5 ——图的大小
0 1 ——起点坐标
3 3 ——终点坐标
1 ——湖泊个数
2 2 ——湖泊坐标
注意:坐标的单位长度为1
输出描述
最短路径有4条,距离是5,输出格式是 4 5
输入
5 5
0 1
3 3
1
2 2
输出
4 5
思路分析
这道题就是经典的回溯问题,可以参考leetcode中:200. 岛屿数量,多加一步撤回操作。
首先将地图存下来,然后回溯判断即可。
参考代码
import java.util.Scanner;
public class findNearestRoad {
public static int minLen = Integer.MAX_VALUE; // 最小路径
public static int path = 0; // 路径条数
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int row = in.nextInt();
int col = in.nextInt();
int[][] map = new int[row][col];
int start_x = in.nextInt();
int start_y = in.nextInt();
int end_x = in.nextInt();
int end_y = in.nextInt();
int num = in.nextInt();
int[][] pool = new int[num][2];
// 将所有点标记为0
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
map[i][j] = 0;
}
}
for (int i = 0; i < num; i++) { // 高山湖泊设为1
pool[i][0] = in.nextInt();
pool[i][1] = in.nextInt();
map[pool[i][0]][pool[i][1]] = 1;
}
dfs(map, 0, start_x, start_y, end_x, end_y);
System.out.println(path + " " + minLen);
}
private static void dfs(int[][] map, int len, int start_x, int start_y, int end_x, int end_y) {
int row = map.length, col = map[0].length;
if (start_x < 0 || start_x >= row || start_y < 0 || start_y >= col || map[start_x][start_y] != 0) { // 越界
return;
}
if (start_x == end_x && start_y == end_y) {
if (len < minLen) {
path = 1;
minLen = len;
} else if (len == minLen) {
path++;
}
return; // 走到终点
} else {
map[start_x][start_y] = 1;
dfs (map, len + 1, start_x + 1, start_y, end_x, end_y);
dfs (map, len + 1, start_x - 1, start_y, end_x, end_y);
dfs (map, len + 1, start_x, start_y + 1, end_x, end_y);
dfs (map, len + 1, start_x, start_y - 1, end_x, end_y);
map[start_x][start_y] = 0;
}
}
}