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!
*/

Related Posts:

  • Y7M3 P2A 練習-5100北二區資訊複賽 1.圈叉連線數問題(zj:a817)      ✔(上次已傳) 2.藏寶問題(zj:a824)               … Read More
  • Y7M2 P2A 練習-2100北二區資訊複賽 1.圈叉連線數問題(zj:a817) 2.藏寶問題(zj:a824)                ✔ 3.小四數學(zj:a825) 4.天氣預測問題(zj:a826)… Read More
  • 09/24排列組合9月24日 研討之排列組合相關檔案( 可列表及下載 )… Read More
  • Y7M2 P2A 練習-1大數相加    ✔ 大數相乘    ✔ n階乘           ✔ 大數相加================ 最多 1000位的兩個非負整數相加 #include &… Read More
  • APCS 105年3月題4-血緣關係(C++參考)APCS Y16M3-Q3 - 血緣關係 /* apcs-4 : 105年3月5日 APCS 試題 Q4 - 血緣關係  , 原題應不需多測資,本參考解為多測資 EOF   找每一葉節點的(最長距len、最大子樹高h1、次大子樹高h2),求max(len, h1+h2)… Read More

0 意見:

張貼留言