2016年7月29日 星期五

a982迷宮問題(C++版)

/*
a982 迷宮問題
*/

#include <iostream>
using namespace std;
const int MaxN = 100;
const int MaxQ = 200;
int main(void)
{
int n,i,j;
int x,y,h;
string s[MaxN];
int qh[MaxQ], qy[MaxQ] , qx[MaxQ];
int p , r ;  // 頭,尾


while( cin >> n ) // a982 只一筆 可不須 while
{
int n1=n-1;  // 起點(1,1)開始  終點(n1-1,n1-1)
for(i=0; i<n; ++i)
cin >> s[i];
// push start 將起點放入 queue 內 h,y,x:步數,列號,行號
p=0;  r=0; h = x = y = 1;
s[y][x] = '#';  // visited 已走過的格子設為 #
  qh[r] = h;  qy[r] = y ; qx[r] = x;  r=(r+1)%MaxQ;  // push 放入 queue尾

  int dy[]={-1,1,0,0};  //上下左右
  int dx[]={0,0,-1,1};
  int ans=0;
while( r!=p && !ans )
{
h = qh[p];  y=qy[p]; x=qx[p];  p=(p+1)%MaxQ;   //pop 由queue頭取出

for( int d=0; d<4; ++d)
{
int ny=y+dy[d], nx=x+dx[d];
  if(ny<1 || ny>=n1 || nx<1 || nx>=n1 ) continue;
if( s[ny][nx] == '#' ) continue;
s[ny][nx] = '#';   // visited
if (ny==n1-1 && nx==n1-1 ) { ans=h+1; break; }
qh[r] = h+1;  qy[r] = ny ; qx[r] = nx;  r=(r+1)%MaxQ;  // push

}
}
if(ans) cout << ans << endl; else cout <<"No solution!\n";
}

return 0;
}
/* 輸入
9
#########
#.......#
#.#####.#
#.......#
##.#.####
#..#.#..#
#.##.##.#
#.......#
#########
9
#########
#.......#
#.#####.#
#.......#
##.#.####
#..#.#..#
#.##.##.#
#...#...#
#########
--------輸出
13
No solution!
*/

0 意見:

張貼留言