题解 | #棋盘游戏#dfs暴力搜索

棋盘游戏

https://www.nowcoder.com/practice/368c98c7bff54a30bba29ae1ba017d55

import java.util.Scanner;
public class Main {
    private static int ans = Integer.MAX_VALUE;
    private static int[][] graph = new int[6][6];
    private static int startX, startY, endX, endY;
    private static int[][] directions = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
    private static boolean[][] visited = new boolean[6][6];
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 6; j++) {
                graph[i][j] = sc.nextInt();
            }
        }
        startX = sc.nextInt();
        startY = sc.nextInt();
        endX = sc.nextInt();
        endY = sc.nextInt();
        dfs(startX, startY, 1, 0);
        System.out.println(ans);
    }
    private static void dfs(int x, int y, int base, int temp) {
        if (x == endX && y == endY) {
            if (temp < ans) {
                ans = temp;
            }
            return;
        }
        visited[x][y] = true;
        for (int[] direction : directions) {
            int nx = x + direction[0];
            int ny = y + direction[1];
            if (nx >= 0 && ny >= 0 && nx < 6 && ny < 6 && !visited[nx][ny]) {
                int cost = graph[nx][ny] * base;
                dfs(nx, ny, cost % 4 + 1, temp + cost);
            }
        }
        visited[x][y] = false;
    }
}

全部评论

相关推荐

10-15 09:13
已编辑
天津大学 soc前端设计
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务