0
我正在編寫騎士的旅行問題,以找到騎士在n * 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.`
在進步,非常感謝你。
我認爲它的位置對我的代碼的結果沒有任何影響。我想知道如果我把它放在兩個不同的位置上,如果我的上面的代碼有差異。 –
它怎麼可能沒有區別,因爲它在第一個代碼中的位置在'if'語句的主體中(因此可能不總是執行),但它在第二個代碼中的位置是無條件的? –