Javascript BFS, easy to understand.
Thinking process:\nSince the target is to minimize the number of road to reverse so that all cities can reach city 0, then for those directly connected to 0, sa
**Thinking process:**\nSince the target is to minimize the number of road to reverse so that all cities can reach city `0`, then for those directly connected to `0`, say `nodes` , if it\'s already in the right direction, no change; if otherwise, reverse it. Same idea applies to the remaining cities that connected to `nodes`.\n\n```javascript\nvar minReorder = function(n, connections) {\n  let ans = 0, nodes = [0];\n  const connSet = new Set(connections);\n  while (nodes.length) {\n    const tmp = new Set(nodes);\n    nodes = [];\n    [...connSet].forEach(c => {\n      if (tmp.has(c[0])) {\n        ans += 1;\n        nodes.push(c[1]);\n        connSet.delete(c);\n      } else if (tmp.has(c[1])) {\n        nodes.push(c[0]);\n        connSet.delete(c);\n      }\n    });\n  }\n  return ans;\n};\n```\n\n**Updated:**\nGot this code below (top 1 performance) from the Submission Detail page, very nice idea. Put it here just for references (modified a little bit to make it more readable for me). Not 100% sure about the rationale behind this code though, I\'ll try my best to interpret it.\n\nThe basic idea is to record the distances for all cities to city `0`, regardless of the direction. So imagine the goal is to reach city `0`, and for one of the roads `[src, dest]`, if the distance from `src` to `0` is greater than distance from `dest` to `0`, it means you are heading to the right direction, like getting nearer towards city `0`. Otherwise, it means you are heading farther from city `0`, then the road should be reversed.\n\n```javascript\nvar minReorder = function(n, connections) {\n  const dist = Array(n).fill(-1);\n  dist[0] = 0;\n  let unknowns = n - 1;\n  while (unknowns) {\n    connections.forEach(([src, dest]) => {\n      if (dist[src] != -1 && dist[dest] == -1) {\n        dist[dest] = dist[src] + 1;\n        --unknowns;\n      } else if (dist[dest] != -1 && dist[src] == -1) {\n        dist[src] = dist[dest] + 1;\n        --unknowns;\n      }\n    });\n  }\n  let ans = 0;\n  connections.forEach(([src, dest]) => {\n    if (dist[src] < dist[dest]) ++ans;\n  });\n  return ans;\n};\n```
['Breadth-First Search', 'JavaScript']