Skip to content

Latest commit

 

History

History
48 lines (41 loc) · 1.12 KB

2022-12-21.md

File metadata and controls

48 lines (41 loc) · 1.12 KB

题目

  1. Possible Bipartition

We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group.

Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way.

思路

bipartite graph

代码

var possibleBipartition = function(n, dislikes) {
  const graph = {}
  const colors = {}

  for (let i = 1; i <= n; i++) {
    graph[i] = []
  }
  for (const d of dislikes) {
    graph[d[0]].push(d[1])
    graph[d[1]].push(d[0])
  }

  function dfs(v, color) {
    colors[v] = color
    for (const adj of graph[v]) {
      if (colors[adj]) {
        if (colors[adj] == colors[v]) {
          return false
        }
      } else {
        if (!dfs(adj, color * -1)) {
          return false
        }
      }
    }
    return true
  }

  for (let i = 1; i <= n; i++) {
    if (!colors[i] && !dfs(i, 1)) {
      return false
    }
  }
  return true
}