1042. 不邻接植花
为保证权益,题目请参考 1042. 不邻接植花(From LeetCode).
解决方案1
CPP
C++
//
// Created by lenovo on 2020/6/8.
//
/**
* 染色问题?
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> gardenNoAdj(int N, vector<vector<int>> &paths) {
vector<vector<int> > vec(N);
vector<int> res(N, 0);
for (auto path:paths) {
vec[path[0] - 1].push_back(path[1]);
vec[path[1] - 1].push_back(path[0]);
}
for (int i = 0; i < N; ++i) {
dfs(vec, res, i);
}
return res;
}
void dfs(vector<vector<int>> &vec, vector<int> &res, int i) {
int color[4] = {0};
for (auto x:vec[i]) {
if (res[x - 1] != 0) {
color[res[x - 1] - 1] = 1;
}
}
for (int j = 0; j < 4; ++j) {
if (color[j] == 0) {
res[i] = j + 1;
break;
}
}
}
};
int main() {
vector<vector<int>> vec;
vector<int> vec1;
vec1.push_back(1);
vec1.push_back(2);
vec.push_back(vec1);
vector<int> vec2;
vec2.push_back(3);
vec2.push_back(4);
vec.push_back(vec2);
// vector<int> vec3;
// vec3.push_back(3);
// vec3.push_back(1);
// vec.push_back(vec3);
Solution so;
for (auto x:so.gardenNoAdj(4, vec)) {
cout << x << endl;
}
return 0;
}
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70