【问题标题】:Finding Shortest Path In A Labyrinth with C用 C 在迷宫中寻找最短路径
【发布时间】:2016-12-24 18:53:17
【问题描述】:

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

#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");
        }

}

它适用于这条路径,但我怎样才能制作更通用的路径?我无法理解堆栈。如果你能给我指路,我可能会使用它。

编辑:添加终点。

已经谢谢你了。

【问题讨论】:

  • 没有终点,也没有可能的出口。
  • 我同意@WeatherVane,不清楚你所说的“作品”是什么意思。 change() 似乎没有被调用,看着它,我很确定它唯一会做的就是无限循环。它会找到一个角落,然后一遍又一遍地进出,不是吗?你有运行change()的版本吗?
  • 您可以查看this answer 和重复链接中的早期迷宫问题。
  • @Weather 抱歉没有提及。我编辑出口。

标签: c


【解决方案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.
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多