zoukankan      html  css  js  c++  java
  • 面试题目-最小代价的寻路问题

    题目:

      给定一个矩阵,表示一张游戏地图,数组中有 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; // 恢复现场
        }
    }
  • 相关阅读:
    波段是金牢记六大诀窍
    zk kafka mariadb scala flink integration
    Oracle 体系结构详解
    图解 Database Buffer Cache 内部原理(二)
    SQL Server 字符集介绍及修改方法演示
    SQL Server 2012 备份与还原详解
    SQL Server 2012 查询数据库中所有表的名称和行数
    SQL Server 2012 查询数据库中表格主键信息
    SQL Server 2012 查询数据库中所有表的索引信息
    图解 Database Buffer Cache 内部原理(一)
  • 原文地址:https://www.cnblogs.com/luo-c/p/13681817.html
Copyright © 2011-2022 走看看