8.图的邻点不同颜色
class Solution { public: vector<int> gardenNoAdj(int N, vector<vector<int>>& paths) { vector<int> G[N]; for (int i=0; i<paths.size(); i++){//建立邻接表 G[paths[i][0]-1].push_back(paths[i][1]-1); G[paths[i][1]-1].push_back(paths[i][0]-1); } vector<int> answer(N,0);//初始化全部未染色 for(int i=0; i<N; i++){//对每个结点 set<int> color{1,2,3,4}; for (int j=0; j<G[i].size(); j++){//当前结点的邻接点 color.erase(answer[G[i][j]]);//把已染过色的去除 } answer[i]=*(color.begin());//染色 } return answer; } };
Johnkram 版
class Solution { public: int h[10005],ne[40005],p[40005],n,m,d[10005],f[10005]; bool v[10005]; void dfs(int x) { v[x]=1; for(int i=h[x];i;i=ne[i])if(!v[p[i]]) { f[p[i]]=x; d[p[i]]=d[x]+1;//深度层 dfs(p[i]); } } vector<int> gardenNoAdj(int N, vector<vector<int>>& paths) { n=paths.size(); int i,j; for(i=m=0;i<n;i++) { p[++m]=paths[i][1]; ne[m]=h[paths[i][0]]; h[paths[i][0]]=m; p[++m]=paths[i][0]; ne[m]=h[paths[i][1]]; h[paths[i][1]]=m; } n=N; vector<int> ans; for(i=1;i<=n;i++)if(!v[i])dfs(i);//防多图 for(i=1;i<=n;i++)ans.push_back(d[i]%2+1); for(i=1;i<=n;i++)for(j=h[i];j;j=ne[j])if(d[p[j]]<d[i]&&p[j]!=f[i]&&ans[i-1]==ans[p[j]-1])ans[p[j]-1]=d[p[j]]%2+3;//防有环 return ans; } };
给跪了。两个%2+1,和%2+3,思路实在是太清晰了!!