我正在编写骑士游览问题,以便在n * n棋盘中找到骑士之旅。我已经做了2个答案,我认为这些答案是完全相同的。但是,在编译时,两个代码产生2个不同的结果。我想知道我的两个代码之间的区别。
这是我的第一个代码: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;
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.`
我的第二个代码:{{3}}
`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.`
事先,非常感谢你。
答案 0 :(得分:0)
var center = Math.floor(myArray.length / 2;
var parity = function(p){
return (p%2)*2-1; //if the number is even, returns -1 otherwise 1
}
//adds to cetner location half on index, signed with its parity, so we get an alternating effect each time index grows bigger
//for 0,1,2,3,4,5,6... will return 0,1,-1,2,-2,3,-3...
var step = function(index){
return (Math.floor((index+1)/2))*parity(index);
}
for (var i=0;i<size;i++){
for (var j=0;j<size;j++){
a[center-step(i)][center-step(j)];
}
}
出现在r[u,v]:=i;
之前的第二个代码中,但不出现在第一个代码中。
有differencing tools可用于分辨两个文本文件的不同之处。熟悉这些工具是个好主意。