POJ-1204-Word Puzzles
http://poj.org/problem?id=1204
字典树加深搜
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
using namespace std;
char map[1005][1005];
int n1,n2;
int xx,yy;
int dirx[8]={-1,-1,0,1,1,1,0,-1};
int diry[8]={0,1,1,1,0,-1,-1,-1};
int out[1005][3];
struct node
{
int count;
node *childs[26];
node()
{
count=0;
for(int i=0;i<26;i++)
childs[i]=NULL;
}
};
node *root,*current,*newnode;
int go(int x,int y)
{
if(0<=x&&x<n1&&0<=y&&y<n2)
return 1;
return 0;
}
void insert(char *str,int t)
{
int i,m;
current=root;
for(i=0;i<strlen(str);i++)
{
m=str[i]-'A';
if(current->childs[m]!=NULL)
current=current->childs[m];
else
{
newnode=new node;
current->childs[m]=newnode;
current=newnode;
}
}
current->count=t;
}
void dfs(node *head,int i,int j,int k)
{
if(head==NULL)
return;
if(head->count!=0)
{
out[head->count][0]=xx;
out[head->count][1]=yy;
out[head->count][2]=k;
head->count=0;
}
if(!go(i,j))
return;
dfs(head->childs[map[i][j]-'A'],i+dirx[k],j+diry[k],k);
}
int main()
{
int i,j,k,t;
char str[1005];
root=new node;
scanf("%d%d%d",&n1,&n2,&t);
for(i=0;i<n1;i++)
scanf("%s",map[i]);
for(i=1;i<=t;i++)
{
scanf("%s",str);
insert(str,i);
}
for(i=0;i<n1;i++)
for(j=0;j<n2;j++)
for(k=0;k<8;k++)
{
xx=i;
yy=j;
dfs(root,i,j,k);
}
for(i=1;i<=t;i++)
printf("%d %d %c\n",out[i][0],out[i][1],out[i][2]+'A');
system("pause");
return 0;
}
本文介绍了解决POJ-1204 WordPuzzles问题的方法,通过构建字典树并结合深度优先搜索实现单词查找。文章详细展示了算法流程,包括地图数据读取、单词插入字典树、搜索过程及结果输出。
2873

被折叠的 条评论
为什么被折叠?



