洛谷P1101 单词方阵

来源:互联网 发布:linux nginx tomcat 编辑:程序博客网 时间:2024/05/23 19:19

单词方阵

问题描述

给一nXn的字母方阵,内可能蕴含多个“yizhong”单词。单词在方阵中是沿着同一方向连续摆放的。摆放可沿着8个方向的任一方向,同一单词摆放时不再改变方向,单词与单词之间可以交叉,因此有可能共用字母。输出时,将不是单词的字母用“*”代替,以突出显示单词。


分析

   经典的dfs,找到一个y就往八个方向搜(要直线搜),搜索中有四个变量,x,y是当前字母的位置,dep为当前到yizhong中的第dep个字母,d为当前搜索方向,当a[x,y]<>ch[dep]时说明这个方向不能组成yizhong,直接退出。


代码


const
  maxn=105;
  dx:array[1..8] of -1..1=(-1,-1,0,1,1,1,0,-1);
  dy:array[1..8] of -1..1=(0,1,1,1,0,-1,-1,-1);
  ch:array[1..7] of char=('y','i','z','h','o','n','g');
var
  a:array[0..maxn,0..maxn] of char;
  f:array[0..maxn,0..maxn] of boolean;
  i,j,n:longint;


function check(x,y:longint):boolean;
begin
  check:=true;
  if (x<1) or (x>n) or (y<1) or (y>n) then exit(false);
end;


function try(x,y,dep,d:longint):boolean;
var
  i:longint;
  fl:boolean;
begin
  fl:=false;
  if a[x,y]<>ch[dep] then exit(false);
  if dep>=7 then begin f[x,y]:=true;exit(true);end; 


  if dep=1
    then begin
           for i:=1 to 8 do
             if check(x+dx[i],y+dy[i]) then
               if try(x+dx[i],y+dy[i],dep+1,i) then
                 begin
                   f[x,y]:=true;
                   fl:=true;
                 end;
         end
    else if check(x+dx[d],y+dy[d]) then
           if try(x+dx[d],y+dy[d],dep+1,d)
             then begin
                    f[x,y]:=true;
                    fl:=true;
                  end;
  if fl then exit(true) else exit(false);
end;


begin
  readln(n);
  for i:=1 to n do
    begin
      for j:=1 to n do
        read(a[i,j]);
      readln;
    end;
  for i:=1 to n do
    for j:=1 to n do
      if a[i,j]='y' then
        if try(i,j,1,0) then f[i,j]:=true else f[i,j]:=false;
  for i:=1 to n do
    for j:=1 to n do
      if not f[i,j] then a[i,j]:='*';
  for i:=1 to n do
    begin
      for j:=1 to n do
        write(a[i,j]);
      writeln;
    end;
end.

0 0
原创粉丝点击