用C搜索迷宫中的最短路径

时间:2016-12-24 18:53:18

标签: c

我想写一个代码来找到迷宫中的最短路径。我写了这个;

#include <stdio.h>

void change (void);
void print(void);

int labirent[13][13] = {
            {1,1,1,1,1,1,1,1,1,1,1,1,1},
            {1,2,0,1,0,0,0,0,0,0,0,0,1},
            {1,0,0,1,0,0,1,0,1,1,1,1,1},
            {1,0,0,1,0,0,1,0,0,0,0,0,1},
            {1,0,0,0,0,0,1,0,0,0,0,0,1},
            {1,0,0,0,0,1,1,1,1,0,0,0,1},
            {1,0,1,1,1,1,1,0,0,0,0,0,1},
            {1,0,0,0,0,1,0,0,0,1,1,1,1},
            {1,0,0,0,0,1,0,0,0,0,0,0,1},
            {1,1,1,1,0,1,0,0,1,1,0,0,1},
            {1,0,0,0,0,1,0,0,1,0,0,1,1},
            {1,0,0,0,0,0,0,0,1,0,0,3,1},
            {1,1,1,1,1,1,1,1,1,1,1,1,1}
    };//defining labyrinth - walls are (1), starting point is (2), null points are (0), end point is (3)

int i = 3;
int a = 0;

int x=1, y=1;//current positions

int main(){

    change();

    print();

 return 0;   
}

void change(){


        if(labirent[x+1][y]==0){
            labirent[x+1][y]=i;
            x = x + 1;
            change();
        }else if(labirent[x][y+1]==0){
            labirent[x][y+1]=i;
            y = y+1;
            change();
        }else if(labirent[x-1][y]==0){
            labirent[x-1][y]=i;
            x = x-1;
            change();
        }else if(labirent[x][y-1]==0){
            labirent[x][y-1]=i;
            y = y -1;
            change();
        }

}
void print(){

    for(int i=0;i<13;i++){
            for(int j=0;j<13;j++){
                printf("%d ",labirent[i][j]);
            }
            printf("\n");
        }

}

它适用于这条道路,但我怎样才能做出更一般的道路呢?我无法理解堆栈。如果你能告诉我,我可以使用它。

编辑:添加终点。

谢谢你。

2 个答案:

答案 0 :(得分:1)

考虑到startend点,解决方案是bfs run。(这是其中一个解决方案)

push s into queue with dist =0
and mark s visited
while( queue is not empty )
{
  x =   front(queue);
  remove x from queue
  foreach unvisited valid neighbor xn of x
      mark xn as visited 
      push it in queue with dist d+1 where d is dist from source to x.
}

答案 1 :(得分:0)

有一次,我必须做同样的事情,练习的目标是实现BackTracking算法:https://en.wikipedia.org/wiki/Backtracking