华为OD机考-上班之路/是否能到达公司-DFS(JAVA 2025B卷)

华为OD机考-上班之路/是否能到达公司-DFS(JAVA 2025B卷)_第1张图片
华为OD机考-上班之路/是否能到达公司-DFS(JAVA 2025B卷)_第2张图片

import java.util.*;
public class GoWork {
    private static final int[][] directions = {{0, 1, 1}, {0, -1, 2}, {1, 0, 3}, {-1, 0, 4}};
    private static int maxTurns, maxClears, rows, cols;
    private static char[][] matrix;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            // 处理输入
            maxTurns = in.nextInt();
            maxClears = in.nextInt();
            rows = in.nextInt();
            cols = in.nextInt();
            in.nextLine();
            matrix = new char[rows][cols];
            for (int i = 0; i < rows; i++) {
                matrix[i] = in.nextLine().toCharArray();
            }
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    boolean[][] visited = new boolean[cols][rows];
                    if (matrix[i][j]=='S') {
                        if (dfs(visited, i, j, 0, 0, 0)) {
                            System.out.println("YES");
                            return;
                        } else {
                            System.out.println("NO");
                            return;
                        }
                    }
                }
            }
            System.out.println("NO");
            return;
        }
    }

    public static boolean dfs(boolean[][] visited, int x, int y, int turnsUsed, int clearsUsed, int lastDirection) {
        if ('T' ==matrix[x][y]) {
            return true;
        }
        visited[x][y] = true;
        for (int[] direction : directions) {
            int curDirection = direction[2];
            int newX = x + direction[0];
            int newY = y + direction[1];

            boolean turnFlag = false;
            boolean breakFlag = false;

            if (newX >= 0 && newX < rows && newY >= 0 && newY < cols && !visited[newX][newY]) {
                if (lastDirection != 0 && lastDirection != curDirection) {
                    if (turnsUsed + 1 > maxTurns) {
                        continue;
                    }
                    turnFlag = true;
                }
                if ('*' ==matrix[newX][newY]) {
                    if (clearsUsed + 1 > maxClears) {
                        continue;
                    }
                    breakFlag = true;
                }
                //只要有任一一个方向走到了公司,那么直接返回true
                if (dfs(visited, newX, newY, turnsUsed + (turnFlag ? 1: 0), clearsUsed + (breakFlag ? 1 : 0), curDirection)) {
                    return true;
                }

            }
        }
        return false;
    }
}

你可能感兴趣的:(华为机考,华为od,宽度优先,算法)