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; } }