forked from strang3-r/Leetcode75
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Flower Planting With No Adjacent.cpp
40 lines (38 loc) · 1.16 KB
/
Flower Planting With No Adjacent.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
bool apply(vector<vector<int>>& adj, vector<int>& colors, int u, int n, int par) {
for (int c = 1; c <= 4; c++) {
if (c != par) {
colors[u] = c;
bool safe = true;
for (int v : adj[u]) {
if (colors[v] == c) {
safe = false;
break;
}
if (colors[v] == -1 && !apply(adj, colors, v, n, c)) {
safe = false;
break;
}
}
if (safe)
break;
colors[u] = -1;
}
}
return colors[u] != -1;
}
public:
vector<int> gardenNoAdj(int N, vector<vector<int>>& paths) {
vector<vector<int>> adj(N);
for (auto e : paths) {
adj[e[0]-1].push_back(e[1]-1);
adj[e[1]-1].push_back(e[0]-1);
}
vector<int> colors(N, -1);
for (int i = 0; i < N; i++) {
if (colors[i] == -1)
apply(adj, colors, i, N, -1);
}
return colors;
}
};