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:
graph
will have length in range[1, 100]
.graph[i]
will contain integers in range[0, graph.length - 1]
.graph[i]
will not containi
or duplicate values.- The graph is undirected: if any element
j
is ingraph[i]
, theni
will 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 ...
随机推荐
- DFS BFS 学习总结
DFS 深度优先搜索 基本思路: if(true) 返回 典型例题: 1.马走日(非常典型) #include<iostream> #include<cstring> usin ...
- CKEditor图片上传问题(默认安装情况下编辑器无法处理图片),通过Base64编码字符串解决
准备做一个文章内容网站,网页编辑器采用CKEditor,第一次用,默认安装情况下,图片无法插入,提示没有定义上传适配器(adapter),错误码提示如下: 根据提示,在官网看到有两种途径:一使用CKE ...
- Forbidden (CSRF token missing or incorrect.):
CSRF令牌失效或丢失,Ajax请求页面报错(403 Forbidden ) csrftoken存在 页面响应为CSRF验证失败请求被中断,经过测试,该错误并非是没有在表单中加入{% csrf_tok ...
- 测试代码的练习——python编程从入门到实践
11-1 城市和国家:编写一个函数,它接受两个形参:一个城市名和一个国家名.这个函数返回一个格式为City,Country的字符串,如Santiago,Chile.这个函数存储在一个名为city_fu ...
- [UOJ #393]【NOI2018】归程
题目大意:有一张$n$个点$m$条边的图,每个边有两个属性$a_i,b_i$.有$Q$个询问,每个询问给出$v,p$,表示所有边中$b_i\leqslant p$的边会被标记,在点$v$,可以通过不被 ...
- Oracle学习笔记(四)
Oracle中的体系结构: oracle体系结构中的进程: 共享池相关的优化: drop table t purge; create table t as select * from dba_obje ...
- 4、线程池(摘自C#高级编程第7版)
1.需求背景 创建线程需要时间.如果有不同的小任务完成,就可以事先创建许多线程,在应完成这些任务时发出请求.这个线程数最好在需要更多的线程时增加,在需要释放资源时减少. 2.线程池出场 不需要自己 ...
- 1 matplotlib绘制折线图
from matplotlib import pyplot as plt #设置图形大小 plt.figure(figsize=(20,8),dpi=80) plt.plot(x,y,color=&q ...
- QueryDSL-JPA
QueryDSL-JPA QueryDSL简介 官网 1 QueryDSL仅仅是一个通用的查询框架,专注于通过Java API构建类型安全的SQL查询. 2 Querydsl可以通过一组通用的查询AP ...
- 一分钟告诉你什么是OPC DA质量代码
[关于TOP Server OPC Server试用版可登录慧都网该产品下载页进行下载] OPC DA(OPC实时数据访问规范)定义了包括数据值,更新时间与数据品质信息的相关标准.这个定义相信大家都很 ...