字符迷阵是一种经典的智力游戏。玩家需要在给定的矩形的字符迷阵中寻找特定的单词。
在这题的规则中,单词是如下规定的:
1. 在字符迷阵中选取一个字符作为单词的开头;
2. 选取右方、下方、或右下45度方向作为单词的延伸方向;
3. 以开头的字符,以选定的延伸方向,把连续得到的若干字符拼接在一起,则称为一个单词。
以图1为例,如果要在其中寻找单词"WORD",则绿色框所标示的都是合法的方案,而红色框所标示的都是不合法的方案。
现在的问题是,给出一个字符迷阵,及一个要寻找的单词,问能在字符迷阵中找到多少个该单词的合法方案。注意合法方案是可以重叠的,如图1所示的字符迷阵,其中单词"WORD"的合法方案有4种。
深度优先搜索。注意方向一旦定了就不能改变了。
手快把'==' 写成了'=',害我debug了半天,气死我了。
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int r, c;
int dx[] = {1, 0, 1};
int dy[] = {0, 1, 1};
bool dfs(vector<string> &G, int y, int x, const string &word, int pos, const int dir)
{
int ny = y + dy[dir];
int nx = x + dx[dir];
if (ny >= r || nx >= c)
return false;
if (word[pos] != G[ny][nx])
return false;
if (pos >= word.size() - 1)
return true;
return dfs(G, ny, nx, word, pos + 1, dir);
}
int main()
{
int n;
cin >> n;
while (n--)
{
cin >> r >> c;
vector<string> G(r);
for (int i = 0; i < r; ++i)
cin >> G[i];
string word;
cin >> word;
//vector<vector<bool>> vis(r, vector<bool>(c, false));
int ans = 0;
for (int i = 0; i < r; ++i)
{
for (int j = 0; j < c; ++j)
{
if (G[i][j] == word[0])
{
if(dfs(G, i, j, word, 1, 0))
++ans;
if (dfs(G, i, j, word, 1, 1))
++ans;
if (dfs(G, i, j, word, 1, 2))
++ans;
}
}
}
cout << ans << endl;
}
}