迷宫问题

/*没细想
dij好做,但是学的很渣
就是非常暴力搜索
甚至没有加剪枝
复杂度很高
每个方向都探查遍
走过的进入一个数组
最后在进行比较
Astar也可以
但是还没学
自己也没搞明白
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
private static int dfs(int[][] maze, int x, int y, boolean[][] flag) {
if (x < 0 || y < 0 || x >= maze.length || y >= maze[0].length) {
return -1;
}
if (flag[x][y]) {
return -1;
}
if (x == maze.length - 1 && y == maze[0].length - 1) {
return maze[maze.length - 1][maze[0].length - 1];
}
flag[x][y] = true;
int minCost = Integer.MAX_VALUE;
int tmpRes = dfs(maze, x + 1, y, flag);
if (tmpRes != -1) {
minCost = Integer.min(minCost, tmpRes);
}
tmpRes = dfs(maze, x - 1, y, flag);
if (tmpRes != -1) {
minCost = Integer.min(minCost, tmpRes);
}
tmpRes = dfs(maze, x, y + 1, flag);
if (tmpRes != -1) {
minCost = Integer.min(minCost, tmpRes);
}
tmpRes = dfs(maze, x, y - 1, flag);
if (tmpRes != -1) {
minCost = Integer.min(minCost, tmpRes);
}
flag[x][y] = false;
return minCost == Integer.MAX_VALUE ? -1 : maze[x][y] + minCost;
}

private static int solve(int[][] maze) {
    boolean[][] flag = new boolean[maze.length][maze[0].length];
    return dfs(maze, 0, 0, flag);
}

public static void main(String[] args) throws FileNotFoundException {
    Scanner in = new Scanner(System.in);
    int mazeSize = in.nextInt();

    for (int i = 0; i < mazeSize; i++) {
        int N = in.nextInt();
        int M = in.nextInt();
        int[][] maze = new int[N][M];
        for (int j = 0; j < N; j++) {
            for (int k = 0; k < M; k++) {
                maze[j][k] = in.nextInt();
            }
        }
        int ans = solve(maze);
        System.out.println(ans);
    }
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值