LF.56.Bipartite
Posted davidnyc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LF.56.Bipartite相关的知识,希望对你有一定的参考价值。
1 /* 2 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. 3 4 Examples 5 6 1 -- 2 7 8 / 9 10 3 -- 4 11 12 is bipartite (1, 3 in group 1 and 2, 4 in group 2). 13 14 1 -- 2 15 16 / | 17 18 3 -- 4 19 20 is not bipartite. 21 22 Assumptions 23 24 The graph is represented by a list of nodes, and the list of nodes is not null. 25 26 */ 27 /** 28 * public class GraphNode { 29 * public int key; 30 * public List<GraphNode> neighbors; 31 * public GraphNode(int key) { 32 * this.key = key; 33 * this.neighbors = new ArrayList<GraphNode>(); 34 * } 35 * } 36 */
1 //node 和 他的邻居 不能是一样的颜色 2 public class Solution { 3 public boolean isBipartite(List<GraphNode> graph) { 4 // write your solution here 5 if (graph == null) { 6 return true ; 7 } 8 Map<GraphNode, Integer> visited = new HashMap<>() ; 9 for ( GraphNode node : graph ) { 10 if (!helper(node, visited)) { 11 return false; 12 } 13 } 14 return true; 15 } 16 private boolean helper(GraphNode node, HashMap<GraphNode, Integer> visited){ 17 //this node already be handled 18 if (visited.containsKey(node)) { 19 return true ; 20 } 21 Queue<GraphNode> queue = new LinkedList<>() ; 22 queue.offer(node); 23 //assign value 24 visited.put(node, 0); 25 while(!queue.isEmpty()){ 26 GraphNode curr = queue.poll() ; 27 List<GraphNode> neighbors = curr.neighbors ; 28 int currColor = visited.get(curr) ; 29 int neiColor = currColor == 0 ? 1 :0 ; 30 for ( GraphNode nei : neighbors) { 31 /*if the nei has not yet been visited, then color it with neiColor, 32 mark it as visited and then offer it */ 33 if (!visited.containsKey(nei)) { 34 visited.put(nei, neiColor); 35 queue.offer(nei); 36 } else{ 37 if (visited.get(nei) != neiColor) { 38 return false ; 39 } 40 /* 41 做图的时候千万要小心,如果 当前点的邻居已经访问过了, 则不要再放入queue 中 42 否则一定死循环 所以图的 bfs 一定要 用一个字典来mark 访问过的点 43 */ 44 } 45 } 46 } 47 return true ; 48 } 49 }
做图的时候千万要小心,如果 当前点的邻居已经访问过了, 则不要再放入queue 中
否则一定死循环 所以图的 bfs 一定要 用一个字典来mark 访问过的点
以上是关于LF.56.Bipartite的主要内容,如果未能解决你的问题,请参考以下文章