算法准备-6.1
不回溯的染色问题
-
描述:
有 N 个花园,按从 1 到 N 标记。在每个花园中,你打算种下四种花之一。
paths[i] = [x, y] 描述了花园 x 到花园 y 的双向路径。
另外,没有花园有 3 条以上的路径可以进入或者离开。
你需要为每个花园选择一种花,使得通过路径相连的任何两个花园中的花的种类互不相同。
以数组形式返回选择的方案作为答案 answer,其中 answer[i] 为在第 (i+1) 个花园中种植的花的种类。花的种类用 1, 2, 3, 4 表示。保证存在答案。
-
思路:题目中的条件保证了不需要回溯,即先求出每个点的邻接点,再遍历所有点即可
-
题解:
class Solution { public int[] gardenNoAdj(int N, int[][] paths) { int[] ans=new int[N];//创建结果数组 //建立邻接点set Map<Integer,Set<Integer>> graph=new HashMap<>(); for(int i=0;i<N;i++) { graph.put(i,new HashSet<>()); } for(int[] path:paths) { int a=path[0]-1; int b=path[1]-1; graph.get(a).add(b); graph.get(b).add(a); } for(int i=0;i<N;i++) { int[] color=new int[5];//想想为什么是五? for(int adj:graph.get(i)) { color[ans[adj]]=1; } for(int j=1;j<=4;j++) { if(color[j]==0) { ans[i]=j; } } } return ans; } }