【Leettcode】785.Is Graph Bipartite?二分圖判斷
阿新 • • 發佈:2022-04-10
There is an undirected graph with n
nodes, where each node is numbered between 0
and n - 1
. You are given a 2D array graph
, where graph[u]
is an array of nodes that node u
is adjacent to. More formally, for each v
in graph[u]
, there is an undirected edge between node u
and node v
. The graph has the following properties:
存在一個 無向圖 ,圖中有 n 個節點。其中每個節點都有一個介於 0 到 n - 1 之間的唯一編號。給你一個二維陣列 graph ,其中 graph[u] 是一個節點陣列,由節點 u 的鄰接節點組成。形式上,對於 graph[u] 中的每個 v ,都存在一條位於節點 u 和節點 v 之間的無向邊。該無向圖同時具有以下屬性:
- There are no self-edges (
graph[u]
does not containu
). - There are no parallel edges (
graph[u]
does not contain duplicate values). - If
v
is ingraph[u]
u
is ingraph[v]
(the graph is undirected). - The graph may not be connected, meaning there may be two nodes
u
andv
such that there is no path between them. - 不存在自環(graph[u] 不包含 u)。
不存在平行邊(graph[u] 不包含重複值)。
如果 v 在 graph[u] 內,那麼 u 也應該在 graph[v] 內(該圖是無向圖)
這個圖可能不是連通圖,也就是說兩個節點 u 和 v 之間可能不存在一條連通彼此的路徑。
A graph is bipartite
A
and B
such that every edge in the graph connects a node in set A
and a node in set B
.
Return true
if and only if it is bipartite.
二分圖 定義:如果能將一個圖的節點集合分割成兩個獨立的子集 A 和 B ,並使圖中的每一條邊的兩個節點一個來自 A 集合,一個來自 B 集合,就將這個圖稱為 二分圖 。
如果圖是二分圖,返回 true ;否則,返回 false 。
Example 1:
Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]] Output: false Explanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.
解釋:不能將節點分割成兩個獨立的子集,
以使每條邊都連通一個子集中的一個節點與另一個子集中的一個節點。
Example 2:
Input: graph = [[1,3],[0,2],[1,3],[0,2]] Output: true Explanation: We can partition the nodes into two sets: {0, 2} and {1, 3}.
解釋:可以將節點分成兩組: {0, 2} 和 {1, 3} 。
Constraints:
graph.length == n
1 <= n <= 100
0 <= graph[u].length < n
0 <= graph[u][i] <= n - 1
-
graph[u]
does not containu
.不會包含 - All the values of
graph[u]
are unique. 所有值互不相同 - If
graph[u]
containsv
, thengraph[v]
containsu
.
JAVA 廣度優先搜尋:
class Solution {
public boolean isBipartite(int[][] graph) {
//廣度優先搜尋
//定義visited陣列,初始值為0表示未被訪問,1和-1表示兩種不同的顏色
int[] visited = new int[graph.length];
//利用佇列進行廣度優先搜尋
Queue<Integer> queue = new LinkedList<>();
//圖中可能含有多個連通區域,需要判斷是否存在頂點未被訪問,若存在則從它開始再遍歷
for(int i=0;i<graph.length;i++){
if(visited[i]!=0)
continue;
//i號結點未被訪問過,入隊
queue.offer(i);
visited[i] = 1; //訪問標記
while(!queue.isEmpty()){
int deQueue = queue.poll(); //隊頭結點出隊
for(int neighbor:graph[deQueue]){ //訪問出隊結點的鄰接點
if(visited[deQueue]==visited[neighbor])
return false; //鄰接點顏色一致 不是二分圖
if(visited[neighbor]==0){
visited[neighbor] = -visited[deQueue]; //與鄰接點著相反顏色
queue.offer(neighbor); //未訪問的鄰接點入隊
}
}
}
}
return true; //所有結點遍歷完畢,未發現鄰接點顏色一致,是二分圖
}
}