Apologies if the title is quite confusing.
I am writing the "Risk" boardgame in Java where the map is a node graph made up of nodes of several colours. I need to write an algorithm which determines if a path (along the solid blank lines) can be found between two nodes, where all nodes between the given two nodes, inclusive, are all of the same colour (the colours of the smaller inner circles, not the larger conitnent coloured circles).
For example, in the given image above:
E Africa to Ural is a valid path (E Africa > Middle East > Afghanistan > Ural are all yellow nodes).
E Africa to Peru is not (N Africa breaks the path of yellow nodes).
At each node, I am able to check the colour of all of its adjacent nodes, move onto one of these adjacent nodes and repeat. What would be the most efficient way to determine if such a path exists?
Thank you for any help in advance.
答案 0 :(得分:1)
Use edge contraction to merge neighboring nodes of the same color to single nodes.
To limit how expensive the update of the graph is, let each node have a pointer to its contraction, and have a method to map a node to its final value. That method will cache the final found contraction.
This makes performing an edge contraction just a question of creating a new node, pointing both old nodes at it, and saying that that node has neighbors = union of neighbor's nodes.
Now your algorithm looks like this:
to_process = all nodes
while to_process:
node = grab one from to_process
if node has been contracted:
skip
else:
for each neighbor:
if neighbor has the same color:
contract node+neighbor
put contracted node in to_process
// All same color paths now have length 1.
search for points connected by a single point