LeetCode 785. Is Graph Bipartite?
原题链接在这里:https://leetcode.com/problems/is-graph-bipartite/
题目:
Given an undirected graph, return true if and only if it is bipartite.
Recall that a graph is bipartite if we can split it's set of nodes into two independent subsets A and B such that every edge in the graph has one node in A and another node in B.
The graph is given in the following form: graph[i] is a list of indexes j for which the edge between nodes i and j exists. Each node is an integer between 0 and graph.length - 1. There are no self edges or parallel edges: graph[i] does not contain i, and it doesn't contain any element twice.
Example 1:
Input: [[1,3], [0,2], [1,3], [0,2]]
Output: true
Explanation:
The graph looks like this:
0----1
| |
| |
3----2
We can divide the vertices into two groups: {0, 2} and {1, 3}.
Example 2:
Input: [[1,2,3], [0,2], [0,1,3], [0,2]]
Output: false
Explanation:
The graph looks like this:
0----1
| \ |
| \ |
3----2
We cannot find a way to divide the set of nodes into two independent subsets.
Note:
graphwill have length in range[1, 100].graph[i]will contain integers in range[0, graph.length - 1].graph[i]will not containior duplicate values.- The graph is undirected: if any element
jis ingraph[i], theniwill be ingraph[j].
题解:
Try to color the nodes with 2 different colors. Two adjcent nodes can't have same colors.
Use BFS to traverse nodes. At the beginning, put node 0 in the queue, color it as 1.
While queue is not empty, poll the cur node. For neighbors, if nei is not traversed before, color nei with -colors[cur].
If nei is traversed and its color is the same as cur, then 2 adjcent nodes have same color, return false.
For questions like this, traversed nodes need to be put into multiple categories, use array of integers to mark their categories.
Note: graph may not be one component. Thus for each node that is still 0, still need BFS on it.
Time Complexity: O(V+E). V = graph.length. E is count of all the edges.
Space: O(V).
AC Java:
class Solution {
public boolean isBipartite(int[][] graph) {
int n = graph.length;
int [] colors = new int[n];
for(int i = 0; i<n; i++){
if(colors[i] == 0){
LinkedList<Integer> que = new LinkedList<>();
colors[i] = 1;
que.add(i);
while(!que.isEmpty()){
int cur = que.poll();
for(int nei : graph[cur]){
if(colors[nei] == 0){
colors[nei] = -colors[cur];
que.add(nei);
}else if(colors[nei] == colors[cur]){
return false;
}
}
}
}
}
return true;
}
}
Use DFS to iterate nodes.
Start with first node with color 0, dfs try to color it with desiredColor.
For its neighbors, if they are not colored before, try to color them with -desiredColor.
Otherwise, check if they have the color they should have.
If any of them not, then return false.
Time Complexity: O(V+E).
Space: O(V). stack space.
AC Java:
class Solution {
public boolean isBipartite(int[][] graph) {
int n = graph.length;
int [] colors = new int[n];
for(int i = 0; i<n; i++){
if(colors[i] == 0 && !dfs(i, 1, colors, graph)){
return false;
}
}
return true;
}
private boolean dfs(int cur, int desiredColor, int [] colors, int[][] graph){
if(colors[cur] == 0){
colors[cur] = desiredColor;
for(int nei : graph[cur]){
if(!dfs(nei, -desiredColor, colors, graph)){
return false;
}
}
return true;
}else if(colors[cur] != desiredColor){
return false;
}else{
return true;
}
}
}
LeetCode 785. Is Graph Bipartite?的更多相关文章
- [leetcode]785. Is Graph Bipartite? [bai'pɑrtait] 判断二分图
Given an undirected graph, return true if and only if it is bipartite. Example 1: Input: [[1,3], [0, ...
- [LeetCode] 785. Is Graph Bipartite? 是二分图么?
Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipart ...
- [LeetCode] 785. Is Graph Bipartite?_Medium tag: DFS, BFS
Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipart ...
- 【LeetCode】785. Is Graph Bipartite? 解题报告(Python)
[LeetCode]785. Is Graph Bipartite? 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu. ...
- 785. Is Graph Bipartite?
Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipart ...
- 785. Is Graph Bipartite?从两个集合中取点构图
[抄题]: Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is ...
- 【LeetCode】图论 graph(共20题)
[133]Clone Graph (2019年3月9日,复习) 给定一个图,返回它的深拷贝. 题解:dfs 或者 bfs 都可以 /* // Definition for a Node. class ...
- [LeetCode] Is Graph Bipartite? 是二分图么?
Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipart ...
- LeetCode - Is Graph Bipartite?
Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipart ...
随机推荐
- 一个 frameset 框架
<frameset border="0" framespacing="0" rows="45,*" frameborder=" ...
- 用Qt实现一个计算器
一· 介绍 目的: 做一个标准型的计算器.用于学习Qt基础学习. 平台: Qt 5.12.0 二· 结构框架设计 2.1最终产品样式 界面的设计大体按照win系统自带的计算器做模仿.左边是win7 的 ...
- python学习-30 总结
小结 1.map函数: 处理序列中的每个元素,得到结果是一个‘列表’,该‘列表’元素个数及位置与原来一样 2.filter:遍历序列中的每个元素,判断每个元素得到的布尔值,如果是True则留下来,例如 ...
- 2019-7-17 正则表达式和re模块
一.re模块与正则表达式之间的关系 正则表达式不是python独有的,它是一门独立的技术 所有的编程语言都可以使用正则 但是如果你想在python中使用,你就必须依赖于re模块 正则的官方定义:正则表 ...
- 原!!Spring redis的Scan的坑,慎用!
线上发现有机器,在发生某块业务大量请求时,后面就没有日志了,查看线程状态,如图1,发现很多线程被阻塞了,查看代码发现,用到了scan,如图2,百度之后,发现该操作不会自动释放redis连接,导致red ...
- ABP 结合 MongoDB 集成依赖注入
1.我们再ABP项目添加一个.NET Core类库 类库名自定定义, 我这里定义为 TexHong_EMWX.MongoDb 添加NuGet包. ABP mongocsharpdriver 添加 A ...
- C#字符串连接问题(包含破折号和引号)
1.需求场景: 生成字符串如下:jsonStr.Append("\"SensorTypes\":"); 解决方法: string code = @"j ...
- 图片Image转换为base64编码的方法
1.FileReader 通过XMLHttpRequest请求图片Blob数据格式,然后利用FileReader转换为dataURL function toDataURL(url, callback) ...
- 140款Android开源优秀项目源码
BeautifulRefreshLayout-漂亮的美食下拉刷新 https://github.com/android-cjj/BeautifulRefreshLayout/tree/Beautifu ...
- linux技能四 用户管理
用户管理:用户类型,添加用户,修改用户,删除用户,查看用户信息,用户的切换,添加组,修改组,删除组,查看组 用户类型:超级用户:root,UID=1 系统用户:运行系统服务的,不能登陆的,UID=(1 ...