Skip to content

Commit 3c6f4cf

Browse files
committed
Add solution #785
1 parent 80201b8 commit 3c6f4cf

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -595,6 +595,7 @@
595595
782|[Transform to Chessboard](./0782-transform-to-chessboard.js)|Hard|
596596
783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy|
597597
784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium|
598+
785|[Is Graph Bipartite?](./0785-is-graph-bipartite.js)|Medium|
598599
790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium|
599600
791|[Custom Sort String](./0791-custom-sort-string.js)|Medium|
600601
796|[Rotate String](./0796-rotate-string.js)|Easy|

solutions/0785-is-graph-bipartite.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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

Comments
 (0)