1. 程式人生 > >NYOJ 迷宮尋寶(一)

NYOJ 迷宮尋寶(一)

char std name sca etc pty n! main algorithm

# include<iostream>
# include<string>
# include<string.h>
# include<queue>
# include<stdio.h>
# include<math.h>
#include <algorithm>
using namespace std;
char d[30][30]; 
int a[5],b[5];
struct Node
{
    int x,y;
    int num;
}node,temp,f[4];
queue<Node> q,q1;
void bfs(int x,int y,int m,int n) { int k; node.x = x; node.y = y; q.push(node); d[x][y] = 0; while(!q.empty()) { temp = q.front(); q.pop(); for(int i=0;i<4;i++) { int t1,t2; t1 = temp.x + f[i].x; t2 = temp.y + f[i].y;
if(t1<0 ||t1>=m || t2<0 || t2>=n) continue; if(d[t1][t2] == G) { printf("YES\n"); return; } else if(d[t1][t2] == 0 || d[t1][t2] == X) { continue; }
else if(d[t1][t2] == A || d[t1][t2] == B || d[t1][t2] == C || d[t1][t2] == D || d[t1][t2] == E) { k = d[t1][t2] - A; if(b[k]>=a[k] && a[k]!=0) { d[t1][t2] = 0; node.x = t1; node.y = t2; q.push(node); } else { node.x = t1; node.y = t2; node.num = k; q1.push(node); } } else if(d[t1][t2] == . || d[t1][t2] == a || d[t1][t2] == b || d[t1][t2] == c || d[t1][t2] == d || d[t1][t2] == e) { if(d[t1][t2]!=.) { k = d[t1][t2] - a; b[k]++; } d[t1][t2] = 0; node.x = t1; node.y = t2; q.push(node); } } if(q.empty()==true && q1.empty()!=true) { k = q1.size(); for(int i=0;i<k;i++) { temp = q1.front(); q1.pop(); if(b[temp.num]>=a[temp.num] && a[temp.num]!=0) { q.push(temp); d[temp.x][temp.y] = 0; } else { q1.push(temp); } } } } //要清空q1 while(!q1.empty()) { q1.pop(); } printf("NO\n"); } int main() { int n,m,i,j,x,y; f[0].x=0;f[0].y=1; f[1].x=0;f[1].y=-1; f[2].x=1;f[2].y=0; f[3].x=-1;f[3].y=0; scanf("%d %d",&m,&n); getchar(); while(n!=0 || m!=0) { for(i=0;i<5;i++) { a[i] = 0; b[i] = 0; } //要重置d數組 for(i=0;i<30;i++) for(j=0;j<30;j++) d[i][j]=0; for(i=0;i<m;i++) { for(j=0;j<n;j++) { scanf("%c",&d[i][j]); if(d[i][j]==S) { x = i; y = j; } if(d[i][j]==a) a[0]++; else if(d[i][j]==b) a[1]++; else if(d[i][j]==c) a[2]++; else if(d[i][j]==d) a[3]++; else if(d[i][j]==e) a[4]++; } getchar(); } bfs(x,y,m,n); /* for(i=0;i<m;i++) { for(j=0;j<n;j++) { printf("%c",d[i][j]); } printf("\n"); } */ scanf("%d %d",&m,&n); //WA原因 少了這句話 getchar(); } return 0; }

NYOJ 迷宮尋寶(一)