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

Commit6e3b0d0

Browse files
authored
Update Is Graph Bipartite.java
1 parent8164bd6 commit6e3b0d0

File tree

1 file changed

+26
-14
lines changed

1 file changed

+26
-14
lines changed

‎Medium/Is Graph Bipartite.java

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,35 @@ public boolean isBipartite(int[][] graph) {
44
int[]color =newint[n];
55
Arrays.fill(color, -1);
66
for (inti =0;i <n;i++) {
7-
if (color[i] == -1) {
8-
Stack<Integer>stack =newStack<>();
9-
stack.push(i);
10-
color[i] =0;
11-
while (!stack.isEmpty()) {
12-
Integernode =stack.pop();
13-
for (Integerneighbor :graph[node]) {
14-
if (color[neighbor] == -1) {
15-
stack.push(neighbor);
16-
color[neighbor] =color[node] ^1;
17-
}
18-
elseif (color[neighbor] ==color[node]) {
19-
returnfalse;
20-
}
7+
if (color[i] == -1 && !bipartiteCheck(graph,i,color)) {
8+
returnfalse;
9+
}
10+
}
11+
returntrue;
12+
}
13+
14+
privatebooleanbipartiteCheck(int[][]graph,intnode,int[]color) {
15+
Queue<Integer>queue =newLinkedList<>();
16+
queue.add(node);
17+
intcurrColor =0;
18+
while (!queue.isEmpty()) {
19+
intsize =queue.size();
20+
while (size-- >0) {
21+
intremoved =queue.remove();
22+
if (color[removed] != -1) {
23+
if (color[removed] !=currColor) {
24+
returnfalse;
25+
}
26+
continue;
27+
}
28+
color[removed] =currColor;
29+
for (intconn :graph[removed]) {
30+
if (color[conn] == -1) {
31+
queue.add(conn);
2132
}
2233
}
2334
}
35+
currColor =currColor ==1 ?0 :1;
2436
}
2537
returntrue;
2638
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp