九宫格算法实现(Delphi版本)

九宫格算法实现(Delphi版本)

九宫格算法实现(Delphi版本)

发现用Delphi写出来的比用C写出来的计算快多了。

program Project1;
{$APPTYPE CONSOLE}

uses
  SysUtils, PerlRegEx, classes;

var
  GG: array[0..8] of array[0..8] of Integer;
const
  QQ:array[0..8] of integer=(0,0,0,3,3,3,6,6,6);

procedure SetGG;
var
  f: TextFile;
  n, m: Integer;
  Reg: TPerlRegEx;
  List: TStrings;
  s: string;
begin
  Reg:=TPerlRegEx.Create(nil);
  List:=TStringList.Create;
  s:='';    n:=0;
  AssignFile(f,'data.txt');
  Reset(f);
  while not eof(f) do
  begin
    Readln(f,s); s:=trim(s);
    if not (s='') then
    begin
      reg.Subject := s;
      reg.RegEx := ' *';
      reg.Split(list,MaxInt);
      for m := 0 to 8 do
      begin
         GG[n,m]:=strtoint(list[m]);
      end;
       n:=n+1;
    end;
  list.Clear;
  end;
  list.Free;
  closefile(f);
end;

procedure OutGG;
var
  I: Integer;
  j: Integer;
begin
  for I := 0 to 9 - 1 do
    for j := 0 to 9 - 1 do
        if (j<>8) then Write(IntToStr(GG[i,j])+' ') else Writeln(GG[i,j]);
  Readln(i);
end;

function IsValid(i,j:integer):boolean;
var n,t,u:integer;
begin
  Result:=true;
  n:=GG[i,j];
  for t := 0 to 9 - 1 do
    if(((t<>i) and (GG[t,j]=n)) or ((t<>j) and (GG[i,t]=n))) then result:=false;

  for t := QQ[i] to QQ[i]+2 do
    for u := QQ[j] to QQ[j] +2 do
      if(((t<>i) or (u<>j)) and (GG[t,u]=n)) then result:=false;
end;

procedure calc(n:integer);
var i,j,k:integer;
begin
  if(n=81) then
  begin
    OutGG;
    Exit;
  end;

  i:=n div 9; j:=n mod 9;

  if(GG[i,j]<>0) then
  begin
    calc(n+1);
    exit;
  end;

  for k := 0 to 9 - 1 do
  begin
    GG[i,j]:=GG[i,j]+1;
    if(IsValid(i,j)) then
    begin
      calc(n+1);
    end;
  end;

  GG[i,j]:=0;

end;

begin
  SetGG;
  calc(0);
  OutGG;
end.