LeetCode 1042. 不邻接植花 ( DFS回溯、一次遍历)

不邻接植花
我这种写法, 实际上借鉴了判断二分图的做法。

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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章