1. 程式人生 > >洛谷 P1101 【單詞方陣】題解

洛谷 P1101 【單詞方陣】題解

body div data freopen DC using stdin 完成後 pac

來先寫一下思路:

1.一一枚舉開始的位置

2.朝8個方向搜索(其實不如說是遞歸)

3.在搜索到後標記搜索到了

4.通過標記在搜索完成後再標記哪些地方是“yizhong”

5.輸出

嚴格來說,此題不算是深搜,到不如說是遞歸,因為只需要往前探路,不需要回溯,下面是代碼:

#include<iostream>
#include<cstdio>
using namespace std;
int pd,wx[9] = {0,-1,-1,0,1,1,1,0,-1},wy[9] = {0,0,1,1,1,0,-1,-1,-1},n,b[101][101];
char st[101][101],dc[9] = " yizhong";
void search(int x,int y,int a,int step){
if(step>7){
pd = 1;
return;
}
if(st[x][y]!=dc[step]||x<1||x>n||y<1||y>n) return;
search(x+wx[a],y+wy[a],a,step+1);
if(pd) b[x][y] = 1;
}
int main(){
freopen("testdata.in","r",stdin);
cin>>n;
for(int i = 1;i<=n;i++)
for(int j = 1;j<=n;j++)
cin>>st[i][j];
for(int i = 1;i<=n;i++)
for(int j = 1;j<=n;j++)
for(int z = 1;z<=8;z++){
pd = 0;
search(i,j,z,1);
}
for(int i = 1;i<=n;i++)
for(int j = 1;j<=n;j++)
if(!b[i][j]) st[i][j] = ‘*‘;
for(int i = 1;i<=n;i++){
for(int j = 1;j<=n;j++)
cout<<st[i][j];
cout<<endl;
}
return 0;
}

總而言之,此題不算特別難,覺得不如單詞接龍,先比之下,此題就較水了,希望對你有幫助!

洛谷 P1101 【單詞方陣】題解