ETH官方钱包

切換
舊版
前往
大廳
主題

【C++】走迷宮!

鍋貼企鵝 | 2012-12-15 08:30:22 | 巴幣 12 | 人氣 5042

  這是一個小程式,他會自己去創(chuàng)造一個迷宮,然後在來走走看可不可以從左上走到右下。然後迷宮創(chuàng)造有對可以走的地方進行加權,不然一開始做幾乎都無法到達右下。  LOL

  實作是運用DFS演算法,算是練功用吧。  XDD


#include<iostream>
#include<ctime>

using namespace std;

bool TRY(int i,int j);

char miku[10][10];

int main()
{
    for(int i=0;i<10;i++)                   //創(chuàng)造迷宮 start
            for(int j=0;j<10;j++)
                    miku[i][j] = 1;
    
    srand(time(0));
    
    for(int i=1;i<9;i++)                    
            for(int j=1;j<9;j++)
                   if(rand()%100 < 65)             
                                 miku[i][j] = 0;     
    miku[1][1] = 0;                            //創(chuàng)造迷宮 end  

    cout << "The origin is: "<<endl;
    for(int i=0;i<10;i++)
    {                
            for(int j=0;j<10;j++)
                    cout << miku[i][j] << " ";
            cout << endl;
    }


    if(TRY(1,1))
    {
                     cout <<endl<< "the solution is " <<endl;
                     for(int i=0;i<10;i++)               
                             for(int j=0;j<10;j++)
                                     if(miku[i][j]==3)
                                                      miku[i][j]=0;
                     for(int i=0;i<10;i++)
                     {                
                                      for(int j=0;j<10;j++)
                                              cout << miku[i][j] << " ";
                               cout << endl;
                     }                     
    }
    else
                     cout <<endl<< "can't solve."<<endl;


    
    system("pause");
    return 0;
}

bool TRY(int i,int j)
{
     if(i==8&&j==8)
     {
                   miku[8][8] = '*';
                   return true;
     }
     if(miku[i][j+1]==0)
     {
                        miku[i][j] = '*';
                        return TRY(i,j+1);
     }
     else if(miku[i+1][j]==0)
          {
                        miku[i][j] = '*';
                        return TRY(i+1,j);
          }
     else if(miku[i-1][j]==0)
          {
                        miku[i][j] = '*';
                        return TRY(i-1,j);     
          }
     else if(miku[i][j-1]==0)
          {
                        miku[i][j] = '*';
                        return TRY(i,j-1);
          }     
     else
     {
         miku[i][j] = 3;
         if(miku[i][j+1]=='*')
                        return TRY(i,j+1);
         else if(miku[i+1][j]=='*')
                        return TRY(i+1,j);
         else if(miku[i-1][j]=='*')
                        return TRY(i-1,j);     
         else if(miku[i][j-1]=='*')
                        return TRY(i,j-1);
         else
                            return false;
     }
}


如果創(chuàng)造出來的迷宮無解。
  
如果創(chuàng)造出來的迷宮有解。   


     

創(chuàng)作回應

OwO~??
可以拿來玩嘛xD
2012-12-15 20:10:16
鍋貼企鵝
他會自己跑跑看,看迷宮可不可以走到最後。 LOL
2012-12-15 20:22:01

更多創(chuàng)作