LeetCode 785 题解

https://leetcode.com/problems/is-graph-bipartite/description/

题目大意:问无向图能否分成两部分,使得两部分的点互相不是直接相连的。

解题思路:从一个点出发染色即可,注意考虑存在多张图的情况。

class Solution {
    public boolean isBipartite(int[][] g) {
        int n = g.length;
        int[] vis = new int[n];
        Queue<Integer> qt = new LinkedList<>();

        for(int j=0;j<n;j++)
        {
            if(vis[j]!=0) continue;
            if(vis[j]==0)
            {
                vis[j]=1;
                qt.offer(j);
            }
            while (!qt.isEmpty()) {
                int t = qt.poll();
//                System.out.println(t);
                for (int i = 0; i < g[t].length; i++) {
                    int tmp = g[t][i];
//                    System.out.println(tmp);
                    if (vis[tmp] == 0) {
                        vis[tmp] = vis[t] * -1;
                        qt.offer(tmp);
                        continue;
                    }
                    
                    if (vis[t] == vis[tmp] * -1) continue;
                    else return false;
                }
            }
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/u011439455/article/details/80485514