zoukankan      html  css  js  c++  java
  • Bipartite

    Determine if an undirected graph is bipartite. A bipartite graph is one in which the nodes can be divided into two groups such that no nodes have direct edges to other nodes in the same group.

    Examples

    1  --   2

        /   

    3  --   4

    is bipartite (1, 3 in group 1 and 2, 4 in group 2).

    1  --   2

        /   |

    3  --   4

    is not bipartite.

    Assumptions

    • The graph is represented by a list of nodes, and the list of nodes is not null.

    M1: BFS

    用map记录每个节点是否visited,0和1表示两种不同颜色

    time: O(n + e), space: O(n)

    /**
     * public class GraphNode {
     *   public int key;
     *   public List<GraphNode> neighbors;
     *   public GraphNode(int key) {
     *     this.key = key;
     *     this.neighbors = new ArrayList<GraphNode>();
     *   }
     * }
     */
    public class Solution {
      public boolean isBipartite(List<GraphNode> graph) {
        // write your solution here
        Map<GraphNode, Integer> visited = new HashMap<>();
        for(GraphNode node : graph) {
          if(!BFS(node, visited)) {
            return false;
          }
        }
        return true;
      }
      
      public boolean BFS(GraphNode node, Map<GraphNode, Integer> visited) {
        if(visited.containsKey(node)) {
          return true;
        }
        Queue<GraphNode> q = new LinkedList<>();
        q.offer(node);
        visited.put(node, 0);
        while(!q.isEmpty()) {
          GraphNode cur = q.poll();
          int curColor = visited.get(cur);
          int neiColor = curColor == 0 ? 1 : 0;
          for(GraphNode nei : cur.neighbors) {
            if(!visited.containsKey(nei)) {
              visited.put(nei, neiColor);
              q.offer(nei);
            } else if(visited.get(nei) != neiColor) {
                return false;
              }
            }
          }
        return true;
      }
    }
  • 相关阅读:
    [AGC019F] Yes or No
    [CF1063F]String Journey
    [Gym100490A] Approximation
    [ARC058C]Iroha and Haiku
    [互测题目]大括号树
    [UVA10859]放置街灯 Placing Lampposts
    PAT甲级1141PAT Ranking of Institutions
    PAT甲级1153Decode Registration Card of PAT
    使用Python语言通过PyQt5和socket实现UDP服务器
    数据结构-哈希
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10268654.html
Copyright © 2011-2022 走看看