fork download
  1. function findPeriodicColorForestRoots(n, edges, colors) {
  2. const graph = Array.from({ length: n }, () => []);
  3.  
  4. for (const [u, v] of edges) {
  5. graph[u].push(v);
  6. graph[v].push(u);
  7. }
  8.  
  9. const order = { R: 0, W: 1, B: 2 };
  10. const seen = Array(n).fill(false);
  11. const answer = [];
  12.  
  13. for (let start = 0; start < n; start++) {
  14. if (seen[start]) continue;
  15.  
  16. const component = [];
  17.  
  18. // BFS 1: Find connected component
  19. const q = [start];
  20. let head = 0;
  21. seen[start] = true;
  22.  
  23. while (head < q.length) {
  24. const u = q[head++];
  25. component.push(u);
  26.  
  27. for (const v of graph[u]) {
  28. if (!seen[v]) {
  29. seen[v] = true;
  30. q.push(v);
  31. }
  32. }
  33. }
  34.  
  35. const valid = [];
  36.  
  37. // Try every node as a potential root
  38. for (const root of component) {
  39. if (isValidRoot(root)) {
  40. valid.push(root);
  41. }
  42. }
  43.  
  44. if (valid.length !== 1) return [];
  45.  
  46. answer.push(valid[0]);
  47. }
  48.  
  49. return answer.sort((a, b) => a - b);
  50.  
  51.  
  52. // BFS 2: Validate a potential root
  53. function isValidRoot(root) {
  54. const q = [[root, -1, 0]];
  55. let head = 0;
  56.  
  57. while (head < q.length) {
  58. const [u, parent, depth] = q[head++];
  59.  
  60. // Check color condition
  61. const actualColor = order[colors[u]];
  62.  
  63. const expectedColor =
  64. (order[colors[root]] + depth) % 3;
  65.  
  66. if (actualColor !== expectedColor) {
  67. return false;
  68. }
  69.  
  70. // Check binary tree condition
  71. const children =
  72. graph[u].length - (parent === -1 ? 0 : 1);
  73.  
  74. if (children > 2) {
  75. return false;
  76. }
  77.  
  78. // Visit children
  79. for (const v of graph[u]) {
  80. if (v !== parent) {
  81. q.push([v, u, depth + 1]);
  82. }
  83. }
  84. }
  85.  
  86. return true;
  87. }
  88. }
Success #stdin #stdout 0.02s 5592KB
stdin
Standard input is empty
stdout
Standard output is empty