字符迷阵

字符迷阵是一种经典的智力游戏。玩家需要在给定的矩形的字符迷阵中寻找特定的单词。

在这题的规则中,单词是如下规定的:

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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值