#include <bits/stdc++.h>
#define change_read() freopen("C:\\Users\\Administrator\\Desktop\\in.txt","r",stdin)
using namespace std;
struct p
{
const static int maxm = 1e3+10;
char mat[maxm][maxm];///store the matrix
};
int changex[8]= {0,0,1,-1,1,1,-1,-1}; ///the direction of the x-axis change
int changey[8]= {1,-1,0,0,1,-1,1,-1}; ///the direction of the y-axis change
const static int maxm = 1e5+10;///the max number of the nodes
int son[maxm][26];///dictionary tree
int num[maxm];///which word in this index
int num_words;///the number of the words
bool app[maxm];///decide the word appear or not
string words[maxm];
p que;///the matrix
int mat_len;///the length of the matrix
int cnt = 0;///the number of the node of the dictionary tree
void add(string que,int len,int ind) ///add the words to the dictionary tree
{
int now = 0;///the index of now
for(int i = 0; i<len; i++)
{
if(son[now][que[i]-'a']==0)
{
son[now][que[i]-'a'] = ++cnt;
}
now = son[now][que[i]-'a'];
}
num[now] = ind;
}
void init() ///initialize the input
{
cin>>mat_len;///read the length of the map
for(int i = 0; i<mat_len; i++)
{
cin>>que.mat[i];///read the map
}
cin>>num_words;///read the length of words
for(int i = 1; i<=num_words; i++) ///read the words
{
cin>>words[i];
add(words[i],words[i].length(),i);
}
}
void dfs(int x,int y,int dir,int now = 0) ///dfs a word
{
if(num[now])
{
app[num[now]] = true;
}
if(son[now][que.mat[x][y]-'a'])
{
dfs(x+changex[dir],y+changey[dir],dir,son[now][que.mat[x][y]-'a']);
}
}
void ans()
{
for(int i = 0; i<mat_len; i++)
{
for(int j = 0; j<mat_len; j++)
{
///enumerate a start point
for(int k = 0; k<8; k++)
{
///enumerate a direction
dfs(i,j,k);
}
}
}
///output the words which appear in the mat
for(int i = 1; i<=num_words; i++)
{
if(app[i]) cout<<words[i]<<endl;
}
}
int main()
{
change_read();
init();
ans();
return 0;
}
运行结果
顺便贴上我巨丑无比的数据生成器
#include <bits/stdc++.h>
#define change_read() freopen("C:\\Users\\Administrator\\Desktop\\in.txt","r",stdin)
#define change_write() freopen("C:\\Users\\Administrator\\Desktop\\out.txt","w",stdout)
#define creat_read() freopen("C:\\Users\\Administrator\\Desktop\\in.txt","w",stdout)
using namespace std;
char mat[1005][1005];
int len;
bool in_map(int x,int y){
if(x<0||x>=len) return false;
if(y<0||y>=len) return false;
return true;
}
int main()
{
creat_read();
srand(time(0));
len = rand()%100;
cout<<len<<endl;
for(int i = 0;i<len;i++){
for(int j = 0;j<len;j++){
mat[i][j] = rand()%26+'a';
cout<<mat[i][j];
}
cout<<endl;
}
int num_words=rand()%1000;
cout<<num_words<<endl;
int changex[8] = {0,0,1,-1,1,1,-1,-1};
int changey[8] = {1,-1,0,0,1,-1,1,-1};
while(num_words--){
int i = rand()%len;
int j = rand()%len;
int dir = rand()%8;
int xxx = rand()%(len>>1)+1;
for(int x = 0;x<xxx;x++){
if(in_map(i,j)){
cout<<mat[i][j];
}
else{
cout<<char(rand()%26+'a');
}
i+=changex[dir];
j+=changey[dir];
}
cout<<endl;
}
return 0;
}