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;
      }
    }
  • 相关阅读:
    OpenFlow Switch学习笔记(一)——基础概念
    Open vSwitch 给虚拟机网卡限流(QoS)
    MySQL字符集或字符序
    timestamp和datetime
    MySQL Audit日志审计
    sysbench0.4.12测试query_cache_size和query_cache_type
    MySQL 异地 双机房同步之otter
    keep running
    Linux Bonding
    自动化测试-2.seleniumIDE
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10268654.html
Copyright © 2011-2022 走看看