leetcode 133, the solution is traversing the graph, so either bfs or dfs should work.
dfs
works like a stack, take an example when processA is running, inside processB is invoked, then processA hang, and go into processB; as processB is running, inside processC is invoked, then processB hanged, and go into processC. e.t.c. so the finished order is from innerest to outest. dfs
will always traverse all possibilities, then return to the outest layer.
in clone graph, e.g.
#0, 1, 2
#1, 2
#2, 2
dfs
process as:
first deal with first line, element 0
, which trick element 1
, so process goes to second line, and trick element 2
, so go to third line(done), then return to second line(done), then return to first line, trick second neighbor 2
go on…
bfs
works different, during processA running, processB is invoked, will still run processA to done, but also push processB to job queue, which will run next time. so using bfs
, usually has a queue
variable to mark unfinished jobs.
|
|