我正在尝试创建一个程序,它将遍历一个随机生成的迷宫,其中1表示通路,0表示墙壁。从左上角开始,到右下角结束。路径可以向上、向下、向左和向右走。
目前,我的程序给出了一条解决方案,但我无法让它打印出多条路径。
我已经阅读了几个不同版本的这个问题,但是我无法找到一个与我的参数完全相符的版本。
以下是我的代码,我省略了随机生成迷宫的部分。
例如,如果我有这个迷宫:
它会给我找到的第一条路径。
目前,我的程序给出了一条解决方案,但我无法让它打印出多条路径。
我已经阅读了几个不同版本的这个问题,但是我无法找到一个与我的参数完全相符的版本。
以下是我的代码,我省略了随机生成迷宫的部分。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
int n, minMatrix, solIndex = 1, minLen = 10000000; //I use the latter 3 variables in order to find the shortest path, not relevant for now
bool solveMaze(int mat[n][n],int x, int y, int sol[][n], int count){
int i, j;
if((!(x >= 0 && x <n && y >=0 && y < n)) || mat[x][y] == 0 || sol[x][y] == 1){
return false;
}
if(x == n-1 && y == n-1){
sol[x][y] = 1;
printf("Solution %d is:\n", solIndex);
for(i = 0; i < n; i++)
{
for( j=0;j<n;j++)
{
printf("%d", sol[i][j]);
}
printf("\n");
}
if(count<minLen)
{
minLen = count;
minMatrix = solIndex;
}
solIndex +=1;
sol[x][y] = 0;
return true;
}
sol[x][y] = 1;
if(solveMaze(mat, x+1, y, sol, count+1)){
return true;
}
if(solveMaze(mat, x-1, y, sol, count+1)){
return true;
}
if(solveMaze(mat, x, y+1, sol, count+1)){
return true;
}
if(solveMaze(mat, x, y-1, sol, count+1)){
return true;
}
sol[x][y] = 0;
return false;
}
我省略了生成迷宫的随机部分。
int main(){
if(!solveMaze(**mat, 0, 0, sol, 0)){
printf("No possible paths, run program again\n");
}
else{
printf("the shortest path is %d\n", minMatrix);
}
}
例如,如果我有这个迷宫:
1100111111
1101111111
1111110110
1110011111
1101101011
1111101011
1110111101
1100111111
1110111011
1101101111
它会给我找到的第一条路径。
1000000000
1001100000
1111110000
1100011000
1100001000
1100001000
1100001000
1100001011
1100001011
1100001111
虽然它需要绕路走,因为它喜欢按照向下、向上、向右和向左的顺序前进,但它仍然是一条路径。
所以,最终,我不知道如何迭代多条路径。