pascal语言出现错误输入数据后程序死循环求解
偶数矩阵:第一行输入n,接下来n行每行输入n个数字(仅0或1),要求将一些0改成1使得矩阵中每个数字的上下左右之和为偶数程序代码如下:varn,t:longint;a,b...
偶数矩阵:第一行输入n,接下来n行每行输入n个数字(仅0或1),要求将一些0改成1使得矩阵中每个数字的上下左右之和为偶数
程序代码如下:
var n,t:longint;
a,b:arr;
i1,i2,it,ans:longint;
function small(a,b:longint):longint;
begin
if a>=b then small:=b
else small:=a;
end;
function wel(s:longint):longint;
var ans,con:longint;
begin
for i1:=0 to n do
for i2:=0 to n do
b[i1,i2]:=0;
for i1:=0 to n do
if (s and (1 shl i1))=0 then b[0,i1]:=0
else if a[0,i1]=1 then
begin
wel:=maxlongint;
exit;
end;
for i1:=1 to n do
for i2:=0 to n do
begin
ans:=0;
if (i1-2)>=0 then ans:=ans+b[i1-2][i2];
if (i2-1)>=0 then ans:=ans+b[i1][i2-1];
if (i2+1)<=n then ans:=ans+b[i1][i2+1];
b[i1,i2]:=ans mod 2;
if (a[i1,i2]=1) and (b[i1,i2]=0) then
begin
wel:=maxlongint;
exit;
end;
end;
con:=0;
for i1:=0 to n-1 do
for i2:=0 to n-1 do
if a[i1,i2]<>b[i1,i2] then con:=con+1;
wel:=con;
end;
begin
ans:=maxlongint;
readln(n);
for i1:=0 to n-1 do
for i2:=0 to n-1 do read(a[i1,i2]);
for i1:=0 to ((1 shl n)-1) do
ans:=small(ans,wel(i1));
if ans=maxlongint then ans:=-1;
writeln(ans);
end. 展开
程序代码如下:
var n,t:longint;
a,b:arr;
i1,i2,it,ans:longint;
function small(a,b:longint):longint;
begin
if a>=b then small:=b
else small:=a;
end;
function wel(s:longint):longint;
var ans,con:longint;
begin
for i1:=0 to n do
for i2:=0 to n do
b[i1,i2]:=0;
for i1:=0 to n do
if (s and (1 shl i1))=0 then b[0,i1]:=0
else if a[0,i1]=1 then
begin
wel:=maxlongint;
exit;
end;
for i1:=1 to n do
for i2:=0 to n do
begin
ans:=0;
if (i1-2)>=0 then ans:=ans+b[i1-2][i2];
if (i2-1)>=0 then ans:=ans+b[i1][i2-1];
if (i2+1)<=n then ans:=ans+b[i1][i2+1];
b[i1,i2]:=ans mod 2;
if (a[i1,i2]=1) and (b[i1,i2]=0) then
begin
wel:=maxlongint;
exit;
end;
end;
con:=0;
for i1:=0 to n-1 do
for i2:=0 to n-1 do
if a[i1,i2]<>b[i1,i2] then con:=con+1;
wel:=con;
end;
begin
ans:=maxlongint;
readln(n);
for i1:=0 to n-1 do
for i2:=0 to n-1 do read(a[i1,i2]);
for i1:=0 to ((1 shl n)-1) do
ans:=small(ans,wel(i1));
if ans=maxlongint then ans:=-1;
writeln(ans);
end. 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询