洛谷P1101单词方阵-DFS

题目链接:洛谷P1101 传送门

在这里插入图片描述
在这里插入图片描述


看完题目,很容易想到8个方向的深搜,比起一般的深搜,本题中每次搜索的方向是唯一的,因此可以在搜索函数中加上方向参数。

我们可以先找的一对连续的‘y’和‘i’来确定开始方向

代码:

#include <stdio.h>
#include <cstring>
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <queue>
#include <deque>
#include <cstring>
#include <iterator>
#include <set>
#include <map>
using namespace std;
#define ll long long
char mp[105][105];
int mov[8][2] = {0, 1, 0, -1, 1, 0, -1, 0, 1, 1, 1, -1, -1, 1, -1, -1};
//八个方向
int mov2[8][2] = {0, -1, 0, 1, -1, 0, 1, 0, -1, -1, -1, 1, 1, -1, 1, 1};
//对应的八个反方向
int vis[105][105];
//标记找到的单词位置
void end(int x, int y, int fx, int step) //回溯七个单次
{
    if (step == 0)
        return;
    x = x + mov2[fx][0];
    y = y + mov2[fx][1];
    vis[x][y] = 1;
    end(x, y, fx, step - 1);
}
string q = "yizhong";
int n;
void dfs(int i, int j, int fx, int num)
{
    if (num == 7)
    {
        end(i, j, fx, 7);
        return;
    }
    else if (q[num] != mp[i][j])
        return;
    int x = i + mov[fx][0];
    int y = j + mov[fx][1];
    if (x < 0 || x > n + 1 || y < 0 || y > n + 1)
        return;
    dfs(x, y, fx, num + 1);
}
int main()
{
    cin >> n;
    for (int i = 1; i <= n; i++)
        cin >> mp[i] + 1;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            if (mp[i][j] == 'y')
            {
                if (mp[i][j + 1] == 'i')
                    dfs(i, j, 0, 0);
                if (mp[i][j - 1] == 'i')
                    dfs(i, j, 1, 0);
                if (mp[i + 1][j] == 'i')
                    dfs(i, j, 2, 0);
                if (mp[i - 1][j] == 'i')
                    dfs(i, j, 3, 0);
                if (mp[i + 1][j + 1] == 'i')
                    dfs(i, j, 4, 0);
                if (mp[i + 1][j - 1] == 'i')
                    dfs(i, j, 5, 0);
                if (mp[i - 1][j + 1] == 'i')
                    dfs(i, j, 6, 0);
                if (mp[i - 1][j - 1] == 'i')
                    dfs(i, j, 7, 0);
            }
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
            if (vis[i][j])
                printf("%c", mp[i][j]);
            else
                printf("*");
        cout << endl;
    }
    return 0;
}
发布了76 篇原创文章 · 获赞 64 · 访问量 9355

猜你喜欢

转载自blog.csdn.net/hesorchen/article/details/104102005