The labarynth (as presented by op) is, of course, 2D, not 3D as op stated.
The code below will, I think, solve the problem, provided each room has a tunnel to at least one higher-numbered room and has no tunnels to itself or to a lower-numbered room. The last bit makes it slightly different, as op said the hamster can't go into a room it's already been in, not that it can't go to a lower-numbered room. But since the given setup shows no backward mobility I've kept it that way.
The setups were chosen arbitrarily from arrays generated by code that's too ugly to post.
Test data:
$setups = array(array(1 => array(2, 3), // 5 rooms, op's problem
2 => array(3),
3 => array(4, 5),
4 => array(5)),
array(1 => array(3, 4, 6), // 6 rooms
2 => array(3, 5),
3 => array(4, 5, 6),
4 => array(5),
5 => array(6)),
array(1 => array(2, 4), // 7 rooms
2 => array(3, 5),
3 => array(4, 5, 7),
4 => array(5, 7),
5 => array(6, 7),
6 => array(7)),
array(1 => array(3), // 8 rooms
2 => array(3, 4),
3 => array(4, 5, 8),
4 => array(6, 7),
5 => array(6, 7),
6 => array(7),
7 => array(8)),
array(1 => array(2, 3, 5, 7), // 9 rooms
2 => array(3, 4),
3 => array(4, 5, 8, 9),
4 => array(6, 7),
5 => array(6, 7),
6 => array(7, 9),
7 => array(8),
8 => array(9)));
foreach ($setups as $setup_num => $rooms) {
$first_room = 1;
$last_room = count($rooms) + 1;
$incomplete_paths = array(array($first_room));
$complete_paths = array();
while (!empty($incomplete_paths)) {
$paths = array();
foreach ($incomplete_paths as $key => $each_path) {
if (end($each_path) == $last_room) {
$complete_paths[] = $each_path;
} else {
foreach ($rooms[end($each_path)] as $dest_room) {
$tmp = $each_path;
$tmp[] = $dest_room;
$paths[] = $tmp;
}
}
}
$incomplete_paths = $paths;
}
echo '<pre>';
echo 'Setup ' . $setup_num . ' has ' . count($complete_paths) . ' solutions<br />';
print_r($complete_paths);
echo '</pre>';
}