886. Possible Bipartition [JavaScript]

本文探讨了一道关于二分图的经典问题,通过构建图并运用深度优先搜索(DFS)进行着色,以判断是否能将人员成功分为两组,避免不喜欢的人进入同一组。该算法适用于解决冲突分配问题。

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

一、题目

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.

二、题目大意

给定N个人,现在需要将这N个人分成两组,但是给定数组dislikes,规定哪些人不能在同一组,如果能够分成两组,那么就返回true,否则false.

三、解题思路

这是一道二分图的问题,采用着色图解决。

四、代码实现
const possibleBipartition = (N, dislikes) => {
  // 构建图
  const graph = new Array(N)
  for (let [x, y] of dislikes) {
    const x1 = x - 1
    const y1 = y - 1
    if (!graph[x1]) {
      graph[x1] = []
    }
    if (!graph[y1]) {
      graph[y1] = []
    }
    graph[x1].push(y1)
    graph[y1].push(x1)
  }
  const colors = new Array(N)
  for (let i = 0; i < colors.length; i++) {
    if (!colors[i] && !dfs(i, 1)) {
      return false
    }
  }
  return true
  function dfs (cur, color) {
    colors[cur] = color
    if (!graph[cur]) {
      return true
    }
    for (let item of graph[cur]) {
      if (colors[item] === color) {
        return false
      }
      if (!colors[item] && !dfs(item, -color)) {
        return false
      }
    }
    return true
  }
}

  如果本文对您有帮助,欢迎关注微信公众号,为您推送更多大前端相关的内容, 欢迎留言讨论,ε=ε=ε=┏(゜ロ゜;)┛。

  您还可以在这些地方找到我:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值