adj
to represent the graph, where adj[node]
contains pairs (neighbor, color)
.answer
with all elements set to -1
, to store the shortest path lengths.visit
to track whether a node has been visited with a particular color.0
with 0
steps and a placeholder color -1
.(node, steps, prevColor)
and iterate over all (neighbor, color)
pairs in adj[node]
.neighbor
has not been visited with color
and color
is not prevColor
, enqueue (neighbor, steps + 1, color)
and update answer[neighbor]
if it's the first visit.answer
array.