2016-12-24 101 views
0

我想寫一段代碼來找到迷宮中最短的路徑。我寫了這個;在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"); 
     } 

} 

它適用於此路徑,但我怎樣才能做出更一般的?我無法理解堆棧。如果你能告訴我方式,我可以使用它。

編輯:終點被添加。

謝謝。

+0

沒有終點或可能退出。 –

+0

我同意@WeatherVane,目前尚不清楚'作品'是什麼意思。 'change()'似乎沒有被調用,並且看着它,我敢肯定它唯一會做的就是無限循環。它會找到一個角落,然後一遍又一遍地進出,不是嗎?你有一個運行'change()'的版本嗎? –

+0

你可以看看[這個答案](http://stackoverflow.com/a/34257513/4142924)和重複鏈接中的早期迷宮問題。 –

回答

1

考慮是有startend點的解決方案是BFS運行(這是解決方案之一)

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. 
}