Skip to content

Commit a7d5803

Browse files
committed
785. Is Graph Bipartite?
1 parent b41d6a8 commit a7d5803

1 file changed

Lines changed: 57 additions & 0 deletions

File tree

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
3+
1. 아이디어 : 인접한 노드는 같은 그룹이 되면 안된다. bfs 로 모든 시작점을 탐색해서, 인접한 노드끼리 같은 그룹일 경우 false
4+
5+
2. 시간복잡도 : O(N+E)
6+
7+
3. 자료구조/알고리즘 : BFS
8+
9+
*/
10+
11+
class Solution {
12+
private List<List<Integer>> g = new ArrayList<>();
13+
private int n;
14+
private int[] visited;
15+
public boolean isBipartite(int[][] graph) {
16+
17+
n = graph.length;
18+
visited = new int[n+1];
19+
20+
for(int i=0; i<n; i++) g.add(new ArrayList<>());
21+
22+
for(int i=0; i<graph.length; i++) {
23+
for(int j=0; j<graph[i].length; j++) {
24+
g.get(i).add(graph[i][j]);
25+
}
26+
}
27+
28+
// 이웃한 노드끼리 다른 그룹
29+
30+
for(int i=0; i<n; i++) {
31+
if(visited[i] != 0) continue;
32+
if(!bfs(i)) return false;
33+
}
34+
35+
return true;
36+
}
37+
38+
private boolean bfs(int start) {
39+
Deque<Integer> dq = new ArrayDeque<>();
40+
41+
dq.add(start);
42+
visited[start] = 1;
43+
44+
while(!dq.isEmpty()) {
45+
int num = dq.poll();
46+
for(int node : g.get(num)) {
47+
if(visited[node] == 0) {
48+
visited[node] = -visited[num];
49+
dq.add(node);
50+
}
51+
else if (visited[num] == visited[node]) return false;
52+
}
53+
}
54+
55+
return true;
56+
}
57+
}

0 commit comments

Comments
 (0)