不鄰接植花
我這種寫法, 實際上借鑑了判斷二分圖的做法。
class Solution {
public:
vector<int> ans;
vector<int> graph[10010];
vector<int> gardenNoAdj(int N, vector<vector<int>>& paths) {
ans.resize(N,0);
for(auto&edge:paths){
graph[edge[0]].push_back(edge[1]);
graph[edge[1]].push_back(edge[0]);
}
for(int i=1;i<=N;i++){
if(ans[i-1]==0){
dfs(i,1);
}
}
return ans;
}
bool dfs(int x,int color){
ans[x-1] = color;
for(int y:graph[x]) {
//如果已經染過色,要麼衝突,要麼回溯。
if(ans[y-1]){
if(ans[y-1]==color){
return false;
}
continue;
}
for(int c=1;c<=4;c++){
if(c!=color){
if(dfs(y,c)){
break;
}
}
}
}
return true;
}
};
其實此題和DFS或者BFS關係都不大,重點是每個點的鄰接點顏色互斥,那麼
class Solution {
public:
vector<int> gardenNoAdj(int N, vector<vector<int>>& paths) {
vector<int> cols(N, 0);
vector<vector<int> > g(N + 1);
for (auto& p : paths) {
g[p[0]].push_back(p[1]);
g[p[1]].push_back(p[0]);
}
for (int i = 1; i <= N; ++i) {
set<int> s{1, 2, 3, 4};
for (auto j : g[i]) {
s.erase(cols[j - 1]);
}
cols[i - 1] = *s.begin();
}
return cols;
}
};