Detect if a graph is bipartite using union find (aka disjoint sets)

不想你离开。 提交于 2019-12-02 14:35:52

Given a graph represented as an adjacency-list (i.e. a list of edges), you can determine if it's bipartite as follows:

  • Initialize a disjoint-set data structure SETS, with a singleton set for each vertex. (If there is an even-length path between two vertices, then we will ultimately unify those two vertices into the same set, unless we return ꜰᴀʟꜱᴇ first.)
  • Initialize a mapping MAP from each vertex to ɴɪʟ. (As we examine edges, we will populate MAP with a mapping from each vertex to one of its neighbors.)
  • For each edge {u, v}:
    • If u and v belong to the same set in SETS, then return ꜰᴀʟꜱᴇ.
    • If MAP[u] = ɴɪʟ, set MAP[u] := v.
      Otherwise, update SETS to unify v with MAP[u].
    • If MAP[v] = ɴɪʟ, set MAP[v] := u.
      Otherwise, update SETS to unify u with MAP[v].
  • Return ᴛʀᴜᴇ.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!