#网易笔试求问4题带障碍物的迷宫DFS为啥只能A 50%呀

这个为啥只能A 50%呀,看很多人说的dp,dp应该不对吧 ,dp只能向下和往右走,很明显不符合题意啊。我是用的dfs,不知道哪里写错了,麻烦帮我看看。感谢谢;
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * <p>
     * 计算最小航行费用
     *
     * @param input int整型二维数组 二维网格
     * @return int整型
     */
    int minRes = Integer.MAX_VALUE;
    int xx[] = {1, 0, -1, 0};
    int yy[] = {0, -1, 0, 1};
    int endX = 0, endY = 0;
    boolean[][] vis;

    public int minSailCost(int[][] input) {
        endX = input.length - 1;
        endY = input[0].length - 1; // write code here
        vis = new boolean[input.length][input[0].length];

        dfs(0, 0, 0, input);
        vis[0][0] = true;
        if (minRes == Integer.MAX_VALUE)
            return -1;
        else
            return minRes;
    }

    public void dfs(int x, int y, int ans, int[][] a) {
        if (ans > minRes)       // 已经有更小的了 ,剪枝直接返回
            return;
        System.out.println(x + " " + y + " " + ans);
        if (x == endX && y == endY) {       //到达重点
            minRes = Math.min(minRes, ans);
            System.out.println("------------------");
            return;

        }
        for (int i = 0; i < 4; i++) {
            int dx = x + xx[i];
            int dy = y + yy[i];

            if (dx >= 0 && dx <= endX && dy >= 0 && dy <= endY) {
                if (!vis[dx][dy] && a[dx][dy] != 2) {  //访问过或者是障碍物
                    vis[dx][dy] = true;
                    int cost = 1;
                    if (a[dx][dy] == 0)
                        cost = 2;
                    else if (a[dx][dy] == 1)
                        cost = 1;
                    dfs(dx, dy, ans + cost, a);
                    vis[dx][dy] = false;
                }
            }
        }
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[][] a = new int[][]{{1, 1, 1, 1, 0}, {0, 1, 0, 1, 0}, {1, 1, 2, 1, 1}, {0, 2, 0, 0, 1}};
        //int[][] a = new int[][]{{1, 1, 1, 1, 1}, {2, 2, 2, 2, 1}, {1, 1, 1, 1, 1}, {1, 2, 2, 2, 2}, {1, 2, 1, 1, 1}};
        System.out.println(sol.minSailCost(a));
    }
}


#网易笔试##网易##笔试题目#
全部评论
我感觉需要判断到达某个点的时候当前长度和之前到达该点长度进行比较,就是在47行加个比较,因为可能你第一种走法走到2,2花费10,但第二种走法走到2,2花费5,因为vis[2][2]被标记了,5这个值不能更新。参考dijkstra
点赞 回复
分享
发布于 2021-08-25 09:36
这是最短路问题,dfs和dp应该都不能过
点赞 回复
分享
发布于 2021-08-29 20:07
联想
校招火热招聘中
官网直投

相关推荐

1 2 评论
分享
牛客网
牛客企业服务