LeetCode: Is Graph Bipartite Solution
1/**2 * @param {number[][]} graph3 * @return {boolean}4 */56const isValid = function (graph, nodeColors, colorToCheck, node) {7 if (nodeColors[node] !== 0) {8 return nodeColors[node] === colorToCheck9 }10 nodeColors[node] = colorToCheck11 for (const adjacentNode of graph[node]) {12 // this is why using color of 1 and -113 if (!isValid(graph, nodeColors, -colorToCheck, adjacentNode)) {14 return false15 }16 }17 return true18}1920var isBipartite = function (graph) {21 const N = graph.length22 // 0: no color, 1: blue, -1: red23 const nodeColors = Array(N).fill(0)2425 // for the case of disconnected graph, check every nodes26 for (let node = 0; node < N; node++) {27 // check if colored yet is equivalent to check if visited yet28 if (nodeColors[node] === 0 && !isValid(graph, nodeColors, 1, node)) {29 return false30 }31 }3233 return true34}
Comments
Loading comments...
Tags
leetcode
graph
bfs
dfs
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Letter Case Permutation
Feb 16, 2021
Previous Post
LeetCode: Shortest Path In Binary Matrix
Feb 14, 2021