通过率为82.35%,但是死活找不出bug在哪

牛牛质数

https://ac.nowcoder.com/acm/contest/6915/A

有没有大佬帮忙看一下,通过率为82.35%,提示请检查是否存在数组越界等非法访问情况,但是死活找不出bug在哪

import java.util.*;

/*
 * public class Point {
 *   int x;
 *   int y;
 * }
 */

public class Solution {
    /**
     * 牛牛经过的房间数。
     * @param n int整型 
     * @param x int整型 
     * @param Edge Point类一维数组 
     * @return int整型
     */
    int[][] dist;
    boolean[][] vis;
    Set<Integer>[] edge;
    public void dfs(int flag,int cur){

        //System.out.println(cur)
        for(int child:edge[cur]){
            if(vis[flag][child]==false){
                vis[flag][child]=true;
                dist[flag][child]=dist[flag][cur]+1;
                dfs(flag,child);
            }
        }
    }
    public int solve (int n, int x, Point[] Edge) {
        // write code here
        if(x==1) return 0;
        int res=0;
        dist=new int[2][n+10];
        vis=new boolean[2][n+10];
        edge=new Set[n+10];
        for(int i=1;i<=n;i++) edge[i]=new HashSet<>();
        for(Point p:Edge){
            edge[p.x].add(p.y);
            edge[p.y].add(p.x);
        }
        vis[0][1]=true;
        vis[1][x]=true;
        dist[0][1]=1;
        dist[1][x]=1;
        dfs(0,1);
        dfs(1,x);
        for(int i=1;i<=n;i++){
            if(dist[0][i]>dist[1][i])
                res=Math.max(res,dist[0][i]);
        }
        return res;
    }
}
全部评论
我和你是一样的错误,最后想到是dfs递归爆栈了,你改成bfs就可以了。
1 回复 分享
发布于 2020-08-15 23:30
求问这个for循环是什么含义?有没有大佬可以给我解释一下。呜呜┭┮﹏┭┮ for(int i=1;i<=n;i++){ if(dist[0][i]>dist[1][i]) res=Math.max(res,dist[0][i]); }
点赞 回复 分享
发布于 2020-08-16 22:02
亲测就是dfs爆栈了,也是换了bfs就过了
点赞 回复 分享
发布于 2020-08-16 19:46
改成bfs就行了
点赞 回复 分享
发布于 2020-08-16 17:40
你把set换成数组试一下,可能是set爆了
点赞 回复 分享
发布于 2020-08-16 17:34
我也是这样,但是我查看别的通过的java代码时,发现了一段神仙代码!!! public int solve (int n, int x, Point[] Edge) { try{ Thread t = new Thread(null,()->{ solve0(n, x, Edge); },"", 1 << 30); t.start(); t.join(); }catch(Exception e){ } // write code here return ans+1; } 我照着他的做法,把dfs的程序另开一个线程,居然真的过了!!,真的过了。 可是搞不懂是什么原理啊。
点赞 回复 分享
发布于 2020-08-16 09:42
c++ 好强啊!!!他们dfs就可以过。要哭了
点赞 回复 分享
发布于 2020-08-15 23:32

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务