Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd5742cb

Browse files
authored
Merge pull requestneetcode-gh#2490 from t3chkid/main
Adds Kotlin dfs & bfs solution for 785. Is Graph Bipartite
2 parents74d2ccf +0666ed3 commitd5742cb

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

‎kotlin/0785-is-graph-bipartite.kt

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
packagekotlin
2+
3+
importjava.util.*
4+
5+
classSolution {
6+
funisBipartiteDfs(graph:Array<IntArray>):Boolean {
7+
if (graph.isEmpty())returntrue
8+
9+
val nodeColorMap= mutableMapOf<Int,Color>()
10+
fundfs(node:Int,defaultColor:Color):Boolean {
11+
if (node!in nodeColorMap.keys) nodeColorMap[node]= defaultColor
12+
for (adjacentNodein graph[node]) {
13+
val isEdgeVisited= nodeColorMap[adjacentNode]!=null
14+
if (isEdgeVisited) {
15+
val colorOfCurrentNode= nodeColorMap.getValue(node)
16+
val colorOfAdjacentNode= nodeColorMap.getValue(adjacentNode)
17+
if (colorOfAdjacentNode== colorOfCurrentNode)returnfalse
18+
elsecontinue
19+
}
20+
if (!dfs(adjacentNode, defaultColor.inverse))returnfalse
21+
}
22+
returntrue
23+
}
24+
25+
for (nodein graph.indices) {
26+
if (nodein nodeColorMap.keys)continue
27+
if (!dfs(node,Color.RED))returnfalse
28+
}
29+
returntrue
30+
}
31+
32+
funisBipartiteBfs(graph:Array<IntArray>):Boolean {
33+
if (graph.isEmpty())returntrue
34+
val nodeColorMap= mutableMapOf<Int,Color>()
35+
36+
funbfs(startNode:Int):Boolean {
37+
// if the node is already colored, return true
38+
if (startNodein nodeColorMap.keys)returntrue
39+
nodeColorMap[startNode]=Color.RED
40+
41+
val queue= (LinkedList<Int>()asQueue<Int>).apply { add(startNode) }
42+
while (queue.isNotEmpty()) {
43+
val currentNode= queue.remove()
44+
val colorOfCurrentNode= nodeColorMap.getValue(currentNode)
45+
for (adjacentNodein graph[currentNode]) {
46+
if (adjacentNodein nodeColorMap.keys) {
47+
val colorOfAdjacentNode= nodeColorMap.getValue(adjacentNode)
48+
if (colorOfAdjacentNode== colorOfCurrentNode)returnfalse
49+
continue
50+
}
51+
nodeColorMap[adjacentNode]= colorOfCurrentNode.inverse
52+
queue.add(adjacentNode)
53+
}
54+
}
55+
returntrue
56+
}
57+
58+
for (nodein graph.indices) {
59+
if (!bfs(node))returnfalse
60+
}
61+
62+
returntrue
63+
}
64+
65+
privateenumclassColor {RED,GREEN }
66+
67+
privatevalColor.inverse
68+
get()=when (this) {
69+
Color.RED->Color.GREEN
70+
Color.GREEN->Color.RED
71+
}
72+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp