题目详情
代码实现
(C#)
public class Solution {
public int[] GardenNoAdj(int N, int[][] paths) {
Dictionary<int, List<int>> graph = new Dictionary<int,List<int>>(); //建立邻接表
for (int i = 0; i < N; i++) {
graph.Add(i, new List<int>()); //初始化邻接表
}
/* 初始化路径信息 */
foreach (int[] path in paths) {
int a = path[0] - 1;//因为数组从0开始而不是从1开始所以减1
int b = path[1] - 1;
graph[a].Add(b);
graph[b].Add(a); //把路径加入邻接表中
}
int[] res = new int[N]; //初始化结果
for (int i = 0; i < N; i++) //从结点i开始
{
bool[] used = new bool[5]; //4种颜色 从1开始 0位置保持不变 同时默认全部为false
/* 查看当前节点的所有邻接点的色彩 */
foreach (int adj in graph[i]) { //遍历List<int>里面的数字 就是遍历i结点的每条路径
used[res[adj]] = true; //把末端已经使用过的颜色标记为true
}
/* 为当前节点染色 */
for (int j = 1; j <= 4; j++) {
if (!used[j]) {
res[i] = j; //如果j位置颜色没有用过 就是把j颜色给结点i
}
}
}
return res;
}
}