题目:
给定一个矩阵,表示一张游戏地图,数组中有 0 和 1 的值,0 表示可以通过,1 表示障碍,不能通过。求:给定一个起点坐标,一个终点坐标,求起点 - 终点的最短路径。《九鼎无双面试题》
思路:
深搜 + 回溯 + 标记 + 恢复。
Java 版:
import java.util.ArrayList; import java.util.List; public class Map { public static void main(String[] args) { int[][] map = new int[][]{ {1,0,1,1,0,0,0}, {0,0,0,0,0,1,0}, {0,1,0,0,1,1,0}, {0,0,0,1,0,0,0}, {1,1,0,0,0,0,1} }; List<Integer> res = new ArrayList<>(); searchMinPath(map,0,1,1,6,0,res); int ans = Integer.MAX_VALUE; for(int value : res){ ans = ans < value ? ans : value; } System.out.println(ans); } public static void searchMinPath(int[][] map,int current_i, int current_j, int end_i, int end_j,int countPath, List<Integer> res){//(current_i, current_j)当前坐标,(end_i, end_j)目标终点坐标;countPath 已经走了多少步了,res 记录走到终点的多少种方式 if(current_i < 0 || current_i >= map.length || current_j < 0 || current_j >= map[0].length || map[current_i][current_j] == -1 || map[current_i][current_j] == 1) return; //出界、走过、是障碍,返回 if(current_i == end_i && current_j == end_j){ // 到达终点 res.add(countPath); // 加入结果集 return; } int tmp = map[current_i][current_j]; // 记录值,以便后面恢复现场 map[current_i][current_j] = -1; // 当前已经走过了,标记为 -1 searchMinPath(map,current_i + 1, current_j,end_i,end_j,countPath + 1, res);//4个方向上遍历 searchMinPath(map,current_i - 1, current_j,end_i,end_j,countPath + 1, res); searchMinPath(map,current_i, current_j + 1,end_i,end_j,countPath + 1, res); searchMinPath(map,current_i, current_j - 1,end_i,end_j,countPath + 1, res); map[current_i][current_j] = tmp; // 恢复现场 } }