|
| 1 | +/** |
| 2 | + * 785. Is Graph Bipartite? |
| 3 | + * https://leetcode.com/problems/is-graph-bipartite/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. |
| 7 | + * You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent |
| 8 | + * to. More formally, for each v in graph[u], there is an undirected edge between node u and |
| 9 | + * node v. The graph has the following properties: |
| 10 | + * - There are no self-edges (graph[u] does not contain u). |
| 11 | + * - There are no parallel edges (graph[u] does not contain duplicate values). |
| 12 | + * - If v is in graph[u], then u is in graph[v] (the graph is undirected). |
| 13 | + * - The graph may not be connected, meaning there may be two nodes u and v such that there is |
| 14 | + * no path between them. |
| 15 | + * |
| 16 | + * A graph is bipartite if the nodes can be partitioned into two independent sets A and B such |
| 17 | + * that every edge in the graph connects a node in set A and a node in set B. |
| 18 | + * |
| 19 | + * Return true if and only if it is bipartite. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[][]} graph |
| 24 | + * @return {boolean} |
| 25 | + */ |
| 26 | +var isBipartite = function(graph) { |
| 27 | + const n = graph.length; |
| 28 | + const colors = new Array(n).fill(-1); |
| 29 | + |
| 30 | + for (let i = 0; i < n; i++) { |
| 31 | + if (colors[i] === -1 && !colorGraph(i, 0, graph, colors)) { |
| 32 | + return false; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + return true; |
| 37 | +}; |
| 38 | + |
| 39 | +function colorGraph(start, color, graph, colors) { |
| 40 | + const queue = [start]; |
| 41 | + colors[start] = color; |
| 42 | + |
| 43 | + while (queue.length > 0) { |
| 44 | + const node = queue.shift(); |
| 45 | + const nextColor = 1 - colors[node]; |
| 46 | + |
| 47 | + for (const neighbor of graph[node]) { |
| 48 | + if (colors[neighbor] === -1) { |
| 49 | + colors[neighbor] = nextColor; |
| 50 | + queue.push(neighbor); |
| 51 | + } else if (colors[neighbor] !== nextColor) { |
| 52 | + return false; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return true; |
| 58 | +} |
0 commit comments