算法练习3:leetcode习题785. Is Graph Bipartite?

本文探讨了如何使用深度优先搜索(DFS)算法来判定一个无向图是否为二分图。通过将节点分为两个独立的子集,并确保每个边连接不同子集的节点,实现了对二分图特性的验证。文章提供了详细的算法思路和C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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.

算法思路

输入:用二维数组表示的一个无向图
输出:判断这个图是否为二分图

这周学习深度优先搜索法在图论研究中的应用,这道题就是很好的一道练习题。根据二分图的性质可知需要存在一个两个子集的划分,任意一条边的两个顶点不在同一个子集。
考虑用深度优先搜索法(DFS),对节点涂双色解决,从一个初始点涂1出发,每到一个节点,检查与此节点有关的边的对应点

  1. 如果对应点没被涂色,则涂上与正在检查的点相反的颜色。
  2. 如果对应点已被涂色,则判断此边的两点颜色是否相同,相同则违反二分图定义,不是二分图,否则继续。
    最后所有节点涂上颜色没有违反二分图定义,则是二分图。

需要注意的是如果存在多个连通分支,DFS递归函数执行完时并没有检查完所有节点,需要在未检查的点中再选一个初始点执行DFS递归,否则判断会出错。

C++代码

class Solution {
public:
//深度搜索的递归实现
    bool helper(vector<vector<int>>& graph, int node, int state[]) {
        for (int i = 0; i < graph[node].size(); ++i) {
            if (state[graph[node][i]] == 0) {
                state[graph[node][i]] = 3 - state[node];
                if (helper(graph, graph[node][i], state) == false)
                {
                    return false;
                }
            }
            else if (state[graph[node][i]] == state[node]) {
                return false;
            }
        }
        return true;
    }
    bool isBipartite(vector<vector<int>>& graph) {
        int state[graph.size()] = {0};
        for (int i = 0; i < graph.size(); ++i)
        {
            if (state[i] == 0)
            {
                state[i] = 1;
                if (helper(graph, i, state) == false)
                {
                    return false;
                }
            }
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值