题目链接:http://www.bjfuacm.com/problem/147/
寻找flash
众所周知,flash学长很喜欢玩游戏。今天,他想和大家玩一个捉迷藏的游戏。flash学长会藏在一个矩阵中并且可以使自己名字中的任意字母大写,现在看聪明的你能不能找到flash了。
(在这个矩阵中,如果将字母横着,竖着或者斜着连在一起能组成flash的任意组合便认为是找到了flash)
输入有多组。每组第一个行为两个整数数n,m(n,m<=10),代表矩阵有n行m列。接下来是一个n*m大小的矩阵。
如果flash藏在这个矩阵中,输出yes,否则输出no。
2 5
FeeSh
alabb
1 5
falsh
yes
no
#include <cstdio> #include <cstring> #include <queue> #include <algorithm> using namespace std; int n, m,flag; char map[15][15]; int vis[15][15]; int dir[][2] = {1,0,1,1,0,1,-1,1,-1,0,-1,-1,0,-1,1,-1}; struct node { int x, y, s; node(int a, int b, int c) { x = a; y = b; s = c; } }; bool juge(int x,int y,int s) { if (s == 2) return map[x][y] == 'l' || map[x][y] == 'L'; else if (s == 3) return map[x][y] == 'a' || map[x][y] == 'A'; else if (s == 4) return map[x][y] == 's' || map[x][y] == 'S'; else if(s==5) return map[x][y] == 'h' || map[x][y] == 'H'; } void bfs(int x, int y) { queue<node>q; memset(vis, 0, sizeof(vis)); vis[x][y] = 1; q.push(node(x,y,1)); while (!q.empty()) { node now = q.front(); q.pop(); if (now.s == 5) { flag = 1; return; } for (int i = 0; i < 8; i++) { int nx = now.x + dir[i][0]; int ny = now.y + dir[i][1]; if (nx<1 || nx>n || ny<1 || ny>m || vis[nx][ny])continue; int sta = now.s+1; //看下一个序号的字符满不满足 if (juge(nx, ny, sta)) { vis[nx][ny] = 1; q.push(node(nx, ny, sta)); } } } } int main() { while (scanf("%d%d", &n, &m) != EOF) { for (int i = 1; i <= n; i++) scanf("%s", map[i] + 1); flag = 0; for (int i = 1; i <= n&&!flag; i++) for (int j = 1; j <= m&&!flag; j++) //flag==1的时候,跳出循环 { if (map[i][j] == 'f' || map[i][j] == 'F') bfs(i, j); } if (flag)printf("yes\n"); else printf("no\n"); } return 0; }
2018-06-03