微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 leetcode 上的一个问题中,在测试用例中检测 Java 中的二部图解决方案失败

如何解决在 leetcode 上的一个问题中,在测试用例中检测 Java 中的二部图解决方案失败

这是我使用 bfs 检测二部图的解决方案。它通过了一个案例,但在 leetcode 上失败了一个测试案例。问题:https://leetcode.com/problems/is-graph-bipartite 测试用例是:[[1,2,3],[0,2],1,2]]。谁能告诉我出了什么问题?

这是我的代码

class Solution {
public boolean isBipartite(int  graph[][]) {
    //ArrayList<ArrayList<Integer>> adj=new ArrayList<>();
    int color[]=new int[graph.length];
    Arrays.fill(color,-1);
 
    for(int i=0;i<graph.length;i++)
    {
        if(color[i]==-1)
        {
        if(!checkbipartite(i,graph,color))
            return false;
        }
    }
    return true;
      
}
public boolean checkbipartite(int node,int graph[][],int color[])
{
    Queue<Integer> q=new LinkedList<>();
    q.add(node);
    color[node]=1;
    while(!q.isEmpty())
    {
        Integer nde=q.poll();
        for(Integer it:graph[node])
        {
            if(color[it]==-1)
            {
                color[it]=1-color[nde];
                q.add(it);
            }
            else if(color[it]==color[nde])
                return false;
        }
    }
    return true;
}

}

解决方法

一个字符可以让一切变得不同:)

我相信这一行:

for(Integer it:graph[node])

应该是:

for(Integer it:graph[nde])

有了这个,您的代码似乎可以工作,至少在问题页面中提供的两个测试用例上是这样。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。