C語言中的資料轉換和定義常量
阿新 • • 發佈:2020-07-16
思路
染色問題,可以使用dfs,也可以使用bfs程式碼
class Solution { boolean valid = true; int[][] graph; public boolean isBipartite(int[][] graph) { this.graph = graph; int n = graph.length; int[] nodes = new int[n]; for(int i = 0; i < n && valid; i++){ //對每一個為著色的結點進行著色 if(nodes[i] == 0){ dfs(i, nodes, 1); } } return valid; } public void dfs( int index, int[] nodes, int color){ nodes[index] = color; for(int neighbor : graph[index]){ //如果鄰居結點未被著色,對其著色 if(nodes[neighbor] == 0){ dfs( neighbor, nodes, -color); if(!valid){ return; } } //如果鄰居結點已經著色,但是和該結點顏色相同,不合法 else if(nodes[neighbor] == color){ valid = false; return; } } } }