1. 程式人生 > >JavaScript刷LeetCode -- 886. Possible Bipartition

JavaScript刷LeetCode -- 886. Possible Bipartition

一、題目

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
  }
}

如果本文對您有幫助,歡迎關注我的微信公眾號【超愛敲程式碼】,為您推送更多內容,ε=ε=ε=┏(゜ロ゜;)┛。