Let's say you are solving your maze with a BFS:
Q.push(initial_position)
visited[initial_position] = true
while !Q.empty
cur = Q.top
for n in cur.neighbors
if (visited[n])
continue;
Q.push(n)
from[n] = cur
visited[n] = true
With visited
, you make sure you don't visit a node twice. With from
, you remember how you get to that node.
So let's change visited
to contain more information:
Q.push(initial_position)
visited[initial_position] = 1
while !Q.empty
cur = Q.top
for n in cur.neighbors
++visited[n]
if (visited[n] > 1)
continue;
Q.push(n)
from[n] = cur
Now visited
doesn't just say if the node is visited, but it says how many times it has been visited. Note that it still doesn't say how many paths there are to it, but simply whether that are more than one paths to it.
However, it is still hard to detect multiple solutions by looking at the goal
. Think about the following maze:
#######
--> -->
# ### #
# ### #
# #
#######
This is how visited
would look like:
#######
-->1111111-->
#1###1#
#1###1#
#11112#
#######
So what we can do is to do another BFS, but this time from the n
where visited[n] > 1
and update visited
:
Q.push(initial_position)
visited[initial_position] = 1
while !Q.empty
cur = Q.top
for n in cur.neighbors
++visited[n]
if (visited[n] > 1)
if (!visited2[n])
Q2.push(n)
visited2[n] = true
continue;
Q.push(n)
from[n] = cur
while !Q2.empty
cur = Q2.top
for n in cur.neighbors
visited[n] = max(visited[n], visited[cur])
if (visited2[n])
continue;
Q.push(n)
visited2[n] = true
Now visited
for the above maze becomes:
#######
-->2222222-->
#2###2#
#2###2#
#22222#
#######
So at this point, by looking at the goal
you can tell if there has been multiple paths to it or not.