原题链接在这里: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 contain i or duplicate values.
  • The graph is undirected: if any element j is in graph[i], then i will be in graph[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;
}
}
}

类似Possible Bipartition.

LeetCode 785. Is Graph Bipartite?的更多相关文章

  1. [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, ...

  2. [LeetCode] 785. Is Graph Bipartite? 是二分图么?

    Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipart ...

  3. [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 ...

  4. 【LeetCode】785. Is Graph Bipartite? 解题报告(Python)

    [LeetCode]785. Is Graph Bipartite? 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu. ...

  5. 785. Is Graph Bipartite?

    Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipart ...

  6. 785. Is Graph Bipartite?从两个集合中取点构图

    [抄题]: Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is  ...

  7. 【LeetCode】图论 graph(共20题)

    [133]Clone Graph (2019年3月9日,复习) 给定一个图,返回它的深拷贝. 题解:dfs 或者 bfs 都可以 /* // Definition for a Node. class ...

  8. [LeetCode] Is Graph Bipartite? 是二分图么?

    Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipart ...

  9. LeetCode - Is Graph Bipartite?

    Given an undirected graph, return true if and only if it is bipartite. Recall that a graph is bipart ...

随机推荐

  1. error adding symbols:DSO missing from command line

    编译时加上-lz,如果是使用eclipse,则在添加库z

  2. Python实现斐波那契递归和尾递归计算

    ##斐波那契递归测试 def fibonacciRecursive(deepth): if deepth == 1: return 1 elif deepth == 2: return 1 else: ...

  3. Go基础编程实践(二)—— 类型转换

    bool to string strconv包的FormatBool函数用于将bool转为string package main import ( "fmt" "strc ...

  4. Docker容器挂载文件(转载)

    一.Docker pull 安装 Nginx 1.查看docker仓库中的 nginx 命令 # 使用 docker search 命令搜索存放在 Docker Hub 中的镜像 docker sea ...

  5. pytest_allure2 生成html报告

    前言      allure是一个report框架,支持java的Junit/testng等框架,当然也可以支持python的pytest,也可以集成到Jenkins上展示高大上的报告界面. 环境准备 ...

  6. 魔法 [线段树优化DP]

    也许更好的阅读体验 \(\mathcal{Description}\) 小 \(D\) 正在研究魔法. 小 \(D\) 得到了远古时期的魔法咒语 \(S\),这个咒语共有 \(n\) 个音节,每个音节 ...

  7. C#基础—数组

    C#基础之数组 1.   数组的定义与初始化 一维数组: (1)            int [] A = new int[4]{ 0,1,2,3}; (2)            int[] B ...

  8. Python基础知识(五)------字典

    Python基础知识(四)------字典 字典 一丶什么是字典 ​ dict关键字 , 以 {} 表示, 以key:value形式保存数据 ,每个逗号分隔 ​ 键: 必须是可哈希,(不可变的数据类型 ...

  9. 基于webpack的前端工程化开发解决方案探索(三):webpack-dev-server

    前两篇中我们使用webpack完成了静态资源(css/js/img)等自动写入HTML模板中,同时还可以为静态资源添加hash版本号,既满足了我们对于静态资源的打包要求,同时又无需开发人员介入打包过程 ...

  10. 个人项目(java实现)

    一.github地址:https://github.com/Moyjing/Moy 二.psp表格 PSP2.1 Personal Software Process Stages 预估耗时(分钟) 实 ...