[leetcode]886. Possible Bipartition

本文详细解析了LeetCode上编号为886的题目“Possible Bipartition”的解决方案。该问题要求将N个人分成两组,使得相互不喜欢的人不会被分在同一组。通过深度优先搜索(DFS)算法,实现了一个有效的解决方案来判断是否可以进行这样的分组。

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

[leetcode]886. Possible Bipartition


Analysis

Still raining outside…—— [每天刷题并不难0.0]

Given a set of N people (numbered 1, 2, …, N), we would like to split everyone into two groups of any size.

Each person may dislike some other people, and they should not go into the same group.

Formally, if dislikes[i] = [a, b], it means it is not allowed to put the people numbered a and b into the same group.

Return true if and only if it is possible to split everyone into two groups in this way.
在这里插入图片描述

Explanation:

Solved by DFS,

  • group[i] = 0 means node i hasn’t been visited.
  • group[i] = 1 means node i has been grouped to 1.
  • group[i] = -1 means node i has been grouped to -1.

Implement

class Solution {
public:
    bool possibleBipartition(int N, vector<vector<int>>& dislikes) {
        vector<vector<int>> graph(N, vector<int>(N));
        for(vector<int> d:dislikes){
            graph[d[0]-1][d[1]-1] = 1;
            graph[d[1]-1][d[0]-1] = 1;
        }
        vector<int> group(N, 0);
        for(int i=0; i<N; i++){
            if(group[i]==0 && !DFS(N, graph, group, i, 1))
                return false;
        }
        return true;
    }
    bool DFS(int N, vector<vector<int>>& graph, vector<int>& group, int idx, int g){
        group[idx] = g;
        for(int i=0; i<N; i++){
            if(graph[idx][i] == 1){
                if(group[i] == g)
                    return false;
                if(group[i] == 0 && !DFS(N, graph, group, i, -g))
                    return false;
            }
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值