题目描述:
说好了,题目不黑人。
给你一个8*8的矩阵,你的初始位置是左下角方格(用’U’表示),你的目标位置是右上角的方格(用’A’表示),其余的62个方格,如果是’.’,表示这个方格为空,如果是’S’,表示这个方格有一块大石头。好了现在你开始从左下角出发,每次可以往上,下,左,右,左上,右上,左下,右下移动一个方格,或者你可以原地不动,一共九个动作方式,在你做完一个动作后,所有的大石头会往下掉一个方格(如果一个大石头的位置是(x,y),那下一秒是(x+1,y),不过如果它已经在最下面的一排了,那它就会掉出矩阵,不再出现),请注意,任一时刻,你不能和某一个大石头处在同一个方格,否则石头会把你XX掉。
现在的问题就是:你能从左下角安全抵达右上角么? 如果能,输出“Yes”,反之,“No”。
输入:
T->测试数据组数(T)。
对于每组数据,输入一个8*8的矩阵,其后有一空行。描述如上。
输出:
对于第i组数据,请输出
Case #i: s(s是一个字符串,如果可以到达,则s为“Yes”,反之“No”)
样例输入:
2
.......A
........
........
........
........
........
........
U.......
.......A
........
........
........
........
.S......
S.......
US......
样例输出:
Case #1: Yes
Case #2: No
实现代码:
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <string>
#include <map>
#include <queue>
#include <stack>
using namespace std;
const int maxn = 1e4 + 10;
const int smaxn = 10;
const int n = 8;//n阶矩阵
int table[smaxn][smaxn] = { 0 };//记录石头的位置
bool inq[smaxn][smaxn] = { false };//记录已入队列的点
int x[9] = { 0,0,1,0,-1,1,1,-1,-1 };//x的操作
int y[9] = { 0,1,0,-1,0,1,-1,1,-1 };//y的操作
int step = 0;//步数
bool flag=false;//是否为原地不动的标志
struct node {
int x, y;
int step;
}S, T, Node;
bool judge(int x, int y) { //判断是否越界
if (x > n || x<1 || y>n || y < 1) {
return false;
}
if (table[x][y] == 1||table[x-1][y]==1) {
return false;
}
if (inq[x][y] == true) {
return false;
}
return true;
}
void adjust() { //进行石头的移动
for (int i = n; i >= 1; i--) {//一定要从后往前移动,否则会出错
for (int j = 1; j <= n; j++) {
if (table[i][j] == 1) {
table[i][j] = 0;
table[i + 1][j] = 1;
}
}
}
}
bool BFS() { //广度优先搜索
queue<node> q;
q.push(S);
int i = 0;
while (!q.empty()) {
node top = q.front();
q.pop();
if (top.x == T.x && top.y == T.y) { //判断是否到达终点
return true;
}
if (top.step != i) { //判断是否到下一层,如果是则移动石头
adjust();
i = top.step;
}
if (table[top.x][top.y] == 1) {//判断石头移动后会不会与当前所处位置重合
continue;
}
for (int i = 0; i < 9; i++) {
if(i == 0){ //此题可以原地不动,故原地不动时忽略“不可访问已入队元素”这一要求
flag = true;
}
int newX = top.x + x[i];
int newY = top.y + y[i];
if (judge(newX, newY)||flag) {//满足需求的进入队列
Node.x = newX;
Node.y = newY;
Node.step = top.step + 1;
q.push(Node);
inq[newX][newY] = true;
}
flag=false;
}
}
return false;
}
int main()
{
int m;
char s;
while (scanf("%d", &m) != EOF) {
for (int i = 0; i < m; i++) {
memset(table, 0, sizeof(table));
memset(inq, 0, sizeof(inq));
step = 0;
for (int j = 1; j <= n; j++) {
getchar();
for (int k = 1; k <= n; k++) {
s = getchar();
while (s == '\n') {
s = getchar();
}
if (s == 'S') {
table[j][k] = 1;
}
if (s == 'U') {
S.x = j;
S.y = k;
S.step = 0;
}
if (s == 'A') {
T.x = j;
T.y = k;
T.step = maxn;
}
}
}
if (BFS()) {
printf("Case #%d: Yes\n", i + 1);
}
else {
printf("Case #%d: No\n", i + 1);
}
}
}
return 0;
}