0

我正在编写 Knight's tour 问题,以便在*n 棋盘中找到骑士的旅行。我做了2个答案,我认为是相同的。但是,编译时,两个代码会产生 2 个不同的结果。我想知道我的两个代码之间的区别。

这是我的第一个代码:http: //ideone.com/WUI7xD

const 
  max = 10;

type 
  square = array [-1..max+1, -1..max+1] of longint;
  vector = array [1..max*max] of longint;

var 
  n : longint;
  x : array [1..8] of longint = (-2, -2, -1, -1, +1, +1, +2, +2);
  y : array [1..8] of longint = (-1, +1, -2, +2, -2, +2, -1, +1);
  c, r : square;
  a, b : vector;
  checking : boolean;

  procedure input;
  begin
    readln(n);
  end;

  procedure backTrack(i, u, v : longint);
  var 
    j : longint;
  begin
    if (i > n * n) then
    begin
      checking := true;
      exit;
    end;

    for j := 1 to 8 do
    begin
      if checking then exit;

      inc(u, x[j]);
      inc(v, y[j]);

      if (u > 0) and (u <= n) and (v > 0) and (v <= n) and (i<=n*n) and (c[u,v] = 0) then
      begin
        c[u, v] := 1;
        r[u, v] := i;
        backTrack(i + 1, u, v);
        c[u, v] := 0;
      end;

      dec(u, x[j]);
      dec(v, y[j]);
    end;
  end;

  procedure solve;
  begin
    fillchar(c, sizeof(c), 0);
    c[1, 1] := 1;
    r[1, 1] := 1;
    checking := false;
    backTrack(2, 1, 1);
  end;

  procedure output;
  var 
    j, i : longint;
  begin
    for j := 1 to n do
    begin
      for i := 1 to n do 
        write(r[i, j], ' ');
  
      writeln;
    end;
  
    readln;
  end;

begin
  input;
  solve;
  output;

end.

我的第二个代码:http: //ideone.com/FdFQuX

const 
  max = 10;
type 
  square = array [-1..max+1, -1..max+1] of longint;  
  vector = array [1..max*max] of longint;
var 
  n : longint;
  x : array [1..8] of longint = (-2, -2, -1, -1, +1, +1, +2, +2);
  y : array [1..8] of longint = (-1, +1, -2, +2, -2, +2, -1, +1);
  c, r : square;
  a, b : vector;
  checking : boolean;

  procedure input;
  begin
    readln(n);
  end;

  procedure backTrack(i, u, v : longint);
  var 
    j : longint;
  begin
    if (i > n * n) then
    begin
      checking := true;
      exit;
    end;

    r[u, v] := i;
  
    for j := 1 to 8 do
    begin
      if checking then exit;
   
      inc(u, x[j]);
      inc(v, y[j]);
  
      if (u > 0) and (u <= n) and (v > 0) and (v <= n) and (i <= n * n) and (c[u, v] = 0) then
      begin
        c[u, v] := 1;
        backTrack(i + 1, u, v);
        c[u, v] := 0;
      end;

      dec(u,x[j]);
      dec(v,y[j]);
    end;
  end;

  procedure solve;
  begin
    fillchar(c, sizeof(c), 0);
    c[1, 1] := 1;
    r[1, 1] := 1;
    checking := false;
    backTrack(1, 1, 1);
  end;

  procedure output;
  var 
    j, i : longint;
  begin
    for j := 1 to n do
    begin
      for i:=1 to n do 
        write(r[i, j], ' ');
   
      writeln;
    end;
  end;

begin
  input;
  solve;
  output;
end.
4

1 回答 1

0

r[u,v]:=i;出现for j:=1 to 8 do在第二个代码之前,但不是第一个。

有一些差异工具可用于区分两个文本文件的不同之处。熟悉这些工具是个好主意。

于 2016-02-04T14:25:48.643 回答