题目链接:洛谷P1101 传送门
看完题目,很容易想到8个方向
的深搜,比起一般的深搜,本题中每次搜索的方向是唯一的,因此可以在搜索函数中加上方向参数。
我们可以先找的一对连续的‘y’和‘i’来确定开始方向
代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
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;
}