785-Is Graph Bipartite?

Description

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].

问题描述

给定无向图, 如果它为双向图, 返回true

如果能将图中的点划分为两个独立的集合A和B, 使得图中的每个边的两个顶点一个在A, 另一个在B, 那么此图为双向图

图以如下形式给出:graph[i]为j的集合, 代表i与集合中的j为一条边的两个顶点。每个顶点为0到graph.length - 1之间的整数。不存在一条边由两个相同的顶点构成, 也不存在平行的边, graph[i]不包含i, 并且不会包含重复顶点。


问题分析

解题关键为通过colors数组来为graph中的顶点标记”颜色”(也就是分组), 颜色color作为递归方法的参数通过!color来改变


解法

class Solution {
    public boolean isBipartite(int[][] graph) {
        int V = graph.length;
        if(V <= 2) return true;

        //用来分组, 注意使用的是对象数组, 因为原始类型有默认值为false
        Boolean[] colors = new Boolean[V];
        for(int i = 0; i < V; i++){
            //注意这里通过null来判断有没有分组
            if(colors[i] == null && !color(graph, colors, true, i)){
                return false;
            }
        }

        return true;
    }

    boolean color(int[][] graph, Boolean[] colors, Boolean color, int node){
        //若已经被分组, 看看是否被分配到了正确的组(也可以说, 是否前后出现矛盾)
        if(colors[node] != null)   return colors[node] == color;

        //分组
        colors[node] = color;
        //与当前节点的数组对立, 因为我们之后递归的为该节点边上的对应顶点
        color = !color;
        //递归相邻顶点
        for(int neighbor : graph[node]){
            if(!color (graph, colors, color, neighbor)){
                return false;
            }
        }

        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值