本题,数据范围较小,我们可以选择四层for循环,也可以选择dfs
这里,我们就用四层for循环来写一下吧
我们的思路就是输入完n*n的格子之后,我们遍历格子,如果搜到了恰好是目标字符的第一个字符,就把这个字符向所有方向遍历,如果有符合要求的单词,我们就把他打上标记
好的,我们来写一下代码
#include <iostream>
using namespace std;
const int N = 110;
int n;
char a[N][N];
string s = "yizhong";
int dx[] = { -1,1,0,0,-1,1,-1,1 };
int dy[] = { 0,0,1,-1,-1,-1,1,1 };
bool st[N][N];
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> a[i][j];
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (a[i][j] == s[0])
{
for (int k = 0; k < 8; k++)
{
int x = i, y = j;
int pos = 0;
int cnt = 0;
while (x<n && x>=0 && y<n && y>=0 &&a[x][y] == s[pos])
{
cnt++;
x = x + dx[k];
y = y + dy[k];
pos++;
if (x > n || x<0 || y>n || y < 0) break;
}
if (cnt == s.size())
{
int x = i, y = j;
int t = cnt;
while (t--)
{
st[x][y] = true;
x = x + dx[k];
y = y + dy[k];
}
}
}
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (!st[i][j]) cout << "*";
else cout << a[i][j];
}
cout << endl;
}
}