1. 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.

分析:

  • 假设两个组:0和1
  • 定义一个hashmap来存放graphNode和组号,并且可以用.containskey()来确定它有没有被访问过
  • 从第一个Node开始expand,然后去看它的邻居是否被visited过:1. 如果有那就看它的key(组号)是不是和这个Node相等,如果相等,直接返回false;如果不想等,ignore;

  2. 如果没有,那就把它存入hashmap中,它的key(组号)和这个Node相反

  • 有任何一个node返回false就可以直接返回false了
  • 全部走完,都没有false,那就true

代码如下:

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
    HashMap<GraphNode, Integer> visited = new HashMap<GraphNode, Integer>();
    for(int i = 0; i < graph.size(); i++) {
       boolean res = BFS(graph.get(i), visited);
       if(res == false) {
         return false; 
       }
    }    
    return true;
  }
  private boolean BFS(GraphNode node, HashMap<GraphNode, Integer> visited) {
    //if this node has been searched, then it does not need to be searched again
     if(visited.containsKey(node)) {
       return true; 
     }
     //two group:0,1
     Queue<GraphNode> q = new LinkedList<GraphNode>();
     q.offer(node);
     visited.put(node, 0);//mark the node as group 0
     //generate its neighbor
     while(!q.isEmpty()) {
       GraphNode cur = q.poll(); 
       for(GraphNode neighbor : cur.neighbors) {
         if(!visited.containsKey(neighbor)) {
            if(visited.get(cur) == 0) {
              visited.put(neighbor, 1);
            }else {
              visited.put(neighbor, 0);
            }
          q.offer(neighbor);
         }else {
           if(visited.get(neighbor) == visited.get(cur)) {
              return false;
           }
         }
       }
     }
    return true;
  }
}
View Code

相关文章:

  • 2021-12-18
  • 2022-02-08
  • 2022-01-26
  • 2022-02-19
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-22
  • 2022-01-05
  • 2022-12-23
  • 2021-12-03
  • 2021-05-29
  • 2021-11-27
相关资源
相似解决方案