题目链接:is-graph-bipartite
题目描述
给定一个无向图graph,当这个图为二分图时返回true。如果我们能将一个图的节点集合分割成两个独立的子集A和B,并使图中的每一条边的两个节点一个来自A集合,一个来自B集合,我们就将这个图称为二分图。graph将会以邻接表方式给出,graph[i]表示图中与节点i相连的所有节点。每个节点都是一个在0到graph.length-1之间的整数。这图中没有自环和平行边: graph[i] 中不存在i,并且graph[i]中没有重复的值。
题目分析
题目比较容易理解,我们只需要使用深搜或者广搜,将节点分成两部分,如果找到某个节点必须在两部分中同时出现,即该图不可二分。
算法
深度优先遍历(Depth-first-Search)
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { public boolean isBipartite(int[][] graph) { Queue<Integer> queue = new LinkedList<>(); int[] colors = new int[graph.length]; for (int i = 0; i < graph.length; i++) { if (colors[i] == 0 && !validColor(graph, colors, 1, i)) return false; } return true; } public boolean validColor(int[][] graph, int[] colors, int color, int node) { if (colors[node] != 0) { return colors[node] == color; } colors[node] = color; for (int j : graph[node]) { if (!validColor(graph, colors, -color, j)) return false; } return true; } }
|
宽度优先遍历(优化)(Breadth-first-Search)
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public boolean isBipartite(int[][] graph) { Queue<Integer> queue = new LinkedList<>(); int[] colors = new int[graph.length]; for (int i = 0; i < graph.length; i++) { if (colors[i] != 0) continue; queue.offer(i); colors[i] = 1; while (!queue.isEmpty()) { int cur = queue.poll(); for (int j : graph[cur]) { if (colors[j] == colors[cur]) return false; if (colors[j] == 0) { colors[j] = -colors[cur]; queue.offer(j); } } } } return true; } }
|