LeetCode-judging bipartite graph

Algorithm record

LeetCode topic:

  There is an undirected graph with n nodes in the graph. Each of these nodes has a unique number between 0 and n - 1. You are given a two-dimensional array graph , where graph[u] is an array of nodes consisting of the adjacent nodes of node u. Formally, for every v in graph[u], there is an undirected edge between node u and node v.

 A graph is called  a bipartite graph   if the set of nodes in a graph can be divided into two independent Asubsets B, and each edge in the graph has two nodes from the  A set and one from  the set  .B


illustrate

1. The topic

输入:graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
输出:false
解释:不能将节点分割成两个独立的子集,以使每条边都连通一个子集中的一个节点与另一个子集中的一个节点。

2. Analysis

  • According to the meaning of the bipartite graph in the title, we need to divide the nodes inside all subgraphs in the entire undirected graph set into two categories, and there are no interconnected edges within the same category.
  • We only need to traverse the graphs in the order in which the current node and the next adjacent node are marked with different values, so as to divide the two classified data nodes.
  • Because there may be many subgraphs, each node needs to be traversed once as the root node. If the root node has been marked, there is no need to go further, saving time.
  • During the traversal process, a node may have been marked, but due to the relationship of other nodes, it needs to be marked again. If the two marked categories are different, it means that the whole graph cannot be divided into two categories, and it can fail quickly, which is marked by a status value. .
class Solution {
    private boolean isRight = true;
    public boolean isBipartite(int[][] graph) {
        int[] color = new int[graph.length];
        for(int i = 0; i < graph.length && isRight; i++) {
            if(color[i] != 0) continue;
            isBipartite(color, graph, 1, i);
        }
        return isRight;
    }
    private void isBipartite(int[] color, int[][] graph, int c, int start) {
        color[start] = c;
        for(int temp : graph[start]) {
            if(color[temp] == 0) {
                isBipartite(color, graph, -c, temp);
                if(!isRight) return;
            } else if(color[temp] != -c) {
                isRight = false;
                return;
            }
        }
    }
}

Summarize

Deep traversal of multiple graphs and classification concepts.

Guess you like

Origin juejin.im/post/7120894789481922574