求助,有四个样例过不了,答案错误

P1746 离开中山路

cbwjl @ 2024-02-13 16:32:06

import java.awt.Point;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
    static int n, x1, y1, x2, y2;
    static char[][] map;
    static int[][] dis;
    static int N=1010;
    static int[] dx = {1, -1, 0, 0};
    static int[] dy = {0, 0, 1, -1};
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        map = new char[N][N];
        dis = new int[N][N];
        for (int i = 1; i <=n; i++) {
            String line = sc.next();
            map[i] = line.toCharArray();
        }
        x1 = sc.nextInt() ; // 减1是因为数组索引从0开始
        y1 = sc.nextInt() ;
        x2 = sc.nextInt() ;
        y2 = sc.nextInt() ;
        int result = bfs();
        System.out.println(result);
    }
    static int bfs() {
        Queue<Point> queue = new LinkedList<>();
        queue.add(new Point(x1, y1));
        dis[x1][y1] = 0; // 起始点到自身的距离是0
        while (!queue.isEmpty()) {
            Point current = queue.poll();
            for (int i = 0; i < 4; i++) {
                int newX = current.x + dx[i];
                int newY = current.y + dy[i];

                if (newX < 1 || newX >=n || newY < 1 || newY >=n) {
                    continue; // 跳过边界外的点
                }

                if (map[newX][newY] != '0') {
                    continue; // 跳过不可走的点
                }

                if (dis[newX][newY] > 0) {
                    continue; // 跳过已经访问过的点
                }
                queue.add(new Point(newX, newY));
                dis[newX][newY] = dis[current.x][current.y] + 1;
                if (newX == x2 && newY == y2) {
                    return dis[newX][newY];
                }
            }
        }
        return 0; // 如果没有找到目标点,返回0表示不可达
    }
}

by liboya5074 @ 2024-02-13 16:52:10

看不懂java


by HuY2397061185 @ 2024-02-20 13:41:09

我也看不懂......


|