【问题标题】:Finding exit from a maze从迷宫中寻找出口
【发布时间】:2021-09-27 15:11:45
【问题描述】:

我为 Coursera 上关于图表的课程中给出的编程作业编写了此代码。在这里输入代码。它通过了问题描述中给出的测试用例,但在提交时失败了我是图表的新手。有人可以帮我找出这段代码中的错误吗?

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Iterator;

public class Reachability {

    private static boolean[] visited;

    private static int reach(ArrayList<Integer>[] adj, int x, int y) {
        if(x == y){
            return 1;
        }
        
        visited[x] = true;
        Iterator itr = adj[x].iterator();
        while(itr.hasNext()){
            x = (int)itr.next();
            if(!visited[x]){
                return reach(adj,x,y);
            }
        }
        return 0;
    }


    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        ArrayList<Integer>[] adj = (ArrayList<Integer>[])new ArrayList[n];
        for (int i = 0; i < n; i++) {
            adj[i] = new ArrayList<Integer>();
        }
        for (int i = 0; i < m; i++) {
            int x, y;
            x = scanner.nextInt();
            y = scanner.nextInt();
            adj[x - 1].add(y - 1);
            adj[y - 1].add(x - 1);
        }
        int x = scanner.nextInt() - 1;
        int y = scanner.nextInt() - 1;
        visited = new boolean[n];
        System.out.println(reach(adj, x, y));
    }
}

下面给出的是失败的测试用例。

失败案例 #6/16:(错误答案)

输入: 100 100 27 96 6 9 81 98 21 94 22 68 76 100 8 50 38 86 71 75 32 93 16 50 71 84 6 72 22 58 7 19 19 76 44 75 24 76 31 35 11 89 42 98 63 92 37 38 20 98 45 91 23 53 37 91 76 93 67 90 12 22 43 52 23 56 67 68 1 21 17 83 63 72 30 32 7 91 50 69 38 44 55 89 15 23 11 72 28 42 22 69 56 79 5 83 55 73 13 72 7 93 20 54 21 55 66 89 2 91 18 88 26 64 11 61 28 59 12 86 42 95 17 82 50 66 66 99 40 71 20 40 5 66 92 95 32 46 7 36 44 94 6 31 19 67 26 57 53 84 10 68 28 74 34 94 25 61 71 88 10 89 28 52 72 79 39 73 11 80 44 79 13 77 30 96 30 53 10 39 1 90 40 91 62 71 44 54 15 17 69 74 13 67 24 69 34 96 21 50 20 91 42 46

您的输出: 0

正确的输出: 1

【问题讨论】:

    标签: java graph-theory maze


    【解决方案1】:

    问题是如果y 不能通过x第一个 未访问邻居到达,你会提前从reach() 返回:

    return reach(adj,x,y);
    

    你想要做的是:

    • 如果可以到达y,则返回 1。
    • 如果无法到达y,则继续下一个邻居

    应该是这样的:

    if (reach(adj, x, y) == 1)
      return 1;
    

    不相关的评论:您可能想要使用Iterator&lt;Integer&gt; 而不是原始类型Integer。这避免了强制转换和编译器警告。

    【讨论】:

    • 'if(!visited[x]){ if(1 ==reach(adj,x,y)){ return 1; } } '
    • 你的意思是这样吗?
    • 非常感谢先生!!!现在它起作用了。我在这方面挣扎了很多。我欠你的!!!
    猜你喜欢
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多