一道很简单的 dfs 题,但是很适合练手。
#include <cstdio>
using namespace std;
const int maxn= 120;
const char target[8]= "yizhong";
int size;
char ch[maxn][maxn], ans[maxn][maxn];
void print_matrix(){
for(int line=0; line<size; ++line){
for(int col=0; col<size; ++col){
putchar(ch[line][col]);
}
putchar('\n');
}
}
enum Direction{
up, down, left, right, up_left, up_right, down_left, down_right
};
bool dfs(int line, int col, Direction dir, int num){
if(line<0 || line>=size || col<0 || col>=size) return false;
if(ch[line][col]==target[num]){
if(num==6){
ans[line][col]= target[num];
return true;
}
int next_line= line, next_col= col;
switch(dir){
case up: --next_line; break;
case down: ++next_line; break;
case left: --next_col; break;
case right: ++next_col; break;
case up_left: --next_line; --next_col; break;
case up_right: --next_line; ++next_col; break;
case down_left: ++next_line; --next_col; break;
case down_right: ++next_line; ++next_col; break;
}
bool ok= dfs(next_line, next_col, dir, num+1);
if(ok) ans[line][col]= target[num];
return ok;
}
return false;
}
int main(){
scanf("%d", &size);
for(int i=0; i<size; ++i){
scanf("%s", ch[i]);
}
//printf("%s\n", target);
//print_matrix();
for(int line=0; line<size; ++line){
for(int col=0; col<size; ++col){
dfs(line, col, up, 0);
dfs(line, col, down, 0);
dfs(line, col, left, 0);
dfs(line, col, right, 0);
dfs(line, col, up_left, 0);
dfs(line, col, up_right, 0);
dfs(line, col, down_left, 0);
dfs(line, col, down_right, 0);
}
}
for(int line=0; line<size; ++line){
for(int col=0; col<size; ++col){
if(ans[line][col]) putchar(ans[line][col]);
else putchar('*');
}
putchar('\n');
}
return 0;
}