You have n gardens, labeled from 1 to n, and an array paths where
paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers.
All gardens have at most 3 paths coming into or leaving it.
Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.
Return _any such a choice as an array _answer, whereanswer[i]is the type of flower planted in the(i+1)thgarden. The flower types are denoted1,2,3, or4. It is guaranteed an answer exists.
Input: n =3, paths =[[1,2],[2,3],[3,1]]Output: [1,2,3]Explanation:
Gardens 1 and 2 have different types.Gardens 2 and 3 have different types.Gardens 3 and 1 have different types.Hence,[1,2,3]is a valid answer. Other valid answers include [1,2,4],[1,4,2], and [3,2,1].
Since each garden has at most 3 neighbors and there are 4 flower types, we can always assign a flower type to each garden such that no two adjacent gardens have the same type. This is a classic greedy coloring problem.
classSolution {
publicint[]gardenNoAdj(int n, int[][] paths) {
List<Integer>[] g =new List[n];
for (int i = 0; i < n; i++) g[i]=new ArrayList<>();
for (int[] p : paths) {
g[p[0]-1].add(p[1]-1);
g[p[1]-1].add(p[0]-1);
}
int[] ans =newint[n];
for (int i = 0; i < n; i++) {
boolean[] used =newboolean[5];
for (int v : g[i]) used[ans[v]]=true;
for (int c = 1; c <= 4; c++) {
if (!used[c]) {
ans[i]= c;
break;
}
}
}
return ans;
}
}
classSolution {
fungardenNoAdj(n: Int, paths: Array<IntArray>): IntArray {
val g = Array(n) { mutableListOf<Int>() }
for (p in paths) {
g[p[0]-1].add(p[1]-1)
g[p[1]-1].add(p[0]-1)
}
val ans = IntArray(n)
for (i in0 until n) {
val used = BooleanArray(5)
for (v in g[i]) used[ans[v]] = truefor (c in1..4) {
if (!used[c]) {
ans[i] = c
break }
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defgardenNoAdj(self, n: int, paths: list[list[int]]) -> list[int]:
g = [[] for _ in range(n)]
for x, y in paths:
g[x-1].append(y-1)
g[y-1].append(x-1)
ans = [0] * n
for i in range(n):
used = {ans[v] for v in g[i]}
for c in range(1, 5):
if c notin used:
ans[i] = c
breakreturn ans
impl Solution {
pubfngarden_no_adj(n: i32, paths: Vec<Vec<i32>>) -> Vec<i32> {
let n = n asusize;
letmut g =vec![vec![]; n];
for p in&paths {
g[(p[0]-1) asusize].push((p[1]-1) asusize);
g[(p[1]-1) asusize].push((p[0]-1) asusize);
}
letmut ans =vec![0; n];
for i in0..n {
letmut used = [false; 5];
for&v in&g[i] {
used[ans[v] asusize] =true;
}
for c in1..=4 {
if!used[c] {
ans[i] = c asi32;
break;
}
}
}
ans
}
}