首页 > 其他 > 详细

LeetCode - 785. Is Graph Bipartite?

时间:2019-08-02 15:01:09      阅读:110      评论:0      收藏:0      [点我收藏+]

判断一个给定图是不是二分图. 题目提供一个用二维数组存储的邻接表. 常规的二分图判断,点着色.

注意要将图存入类中,因为dfs需要访问图中的点.

 

 1 class Solution {
 2     private int[][] graph;
 3     private boolean[] visited;
 4     private int[] colors;
 5 
 6     public boolean isBipartite(int[][] graph) {
 7         this.graph = graph;
 8         int V = graph.length;
 9         visited = new boolean[V];
10         colors = new int[V];
11 
12         for (int v = 0; v < V; v++)
13             if (!visited[v])
14                 if(!dfs(v, 0))
15                     return false;
16         return true;
17     }
18 
19     private boolean dfs(int v, int color) {
20         visited[v] = true;
21         colors[v] = color;
22         for (int w : graph[v]) {
23             if (!visited[w]) {
24                 if (!dfs(w, 1 - color))
25                     return false;
26             }
27             else if (colors[v] == colors[w])
28                 return false;
29         }
30         return true;
31     }
32 }

LeetCode - 785. Is Graph Bipartite?

原文:https://www.cnblogs.com/AntonLiu/p/11288250.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!