生活随笔
收集整理的這篇文章主要介紹了
[Leetcode][第785题][JAVA][判断二分图][BFS][DFS]
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
【問題描述】[中等]
【解答思路】
1. DFS 深度優(yōu)先遍歷
時間復雜度:O(N+M) 空間復雜度:O(N)
class Solution {private static final int UNCOLORED
= 0;private static final int RED
= 1;private static final int GREEN
= 2;private int[] color
;private boolean valid
;public boolean isBipartite(int[][] graph
) {int n
= graph
.length
;valid
= true;color
= new int[n
];Arrays
.fill(color
, UNCOLORED
);for (int i
= 0; i
< n
&& valid
; ++i
) {if (color
[i
] == UNCOLORED
) {dfs(i
, RED
, graph
);}}return valid
;}public void dfs(int node
, int c
, int[][] graph
) {color
[node
] = c
;int cNei
= c
== RED
? GREEN
: RED
;for (int neighbor
: graph
[node
]) {if (color
[neighbor
] == UNCOLORED
) {dfs(neighbor
, cNei
, graph
);if (!valid
) {return;}} else if (color
[neighbor
] != cNei
) {valid
= false;return;}}}
}
2. 廣度優(yōu)先遍歷 BFS
時間復雜度:O(N+M) 空間復雜度:O(N)
class Solution {private static final int UNCOLORED
= 0;private static final int RED
= 1;private static final int GREEN
= 2;private int[] color
;public boolean isBipartite(int[][] graph
) {int n
= graph
.length
;color
= new int[n
];Arrays
.fill(color
, UNCOLORED
);for (int i
= 0; i
< n
; ++i
) {if (color
[i
] == UNCOLORED
) {Queue
<Integer> queue
= new LinkedList<Integer>();queue
.offer(i
);color
[i
] = RED
;while (!queue
.isEmpty()) {int node
= queue
.poll();int cNei
= color
[node
] == RED
? GREEN
: RED
;for (int neighbor
: graph
[node
]) {if (color
[neighbor
] == UNCOLORED
) {queue
.offer(neighbor
);color
[neighbor
] = cNei
;} else if (color
[neighbor
] != cNei
) {return false;}}}}}return true;}
}
【總結(jié)】
1. 深度優(yōu)先遍歷 棧/遞歸 廣度優(yōu)先遍歷 隊列
2有向圖、無向圖 、樹 ----> BFS DFS思想
轉(zhuǎn)載鏈接:https://leetcode-cn.com/problems/is-graph-bipartite/solution/pan-duan-er-fen-tu-by-leetcode-solution/
總結(jié)
以上是生活随笔為你收集整理的[Leetcode][第785题][JAVA][判断二分图][BFS][DFS]的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。