Wikioi 天梯 蛇形矩阵(1160)

小明玩一个数字游戏,取个n行n列数字矩阵(其中n为不超过100的奇数),数字的填补方法为:在矩阵中心从1开始以逆时针方向绕行,逐圈扩大,直到n行n列填满数字,请输出该n行n列正方形矩阵以及其的对角线数字之和.

n(即n行n列)

n+1行,n行为组成的矩阵,最后一行为对角线数字之和

3

5 4 3
6 1 2
7 8 9
25




模拟模拟,你手工怎么搞,程序就怎么搞~~~

画一个蛇形矩阵,笔者的画法是一圈圈画!(QAQ)

那么画一圈就要绕四下,每下画出的是(层数-1)个数~~~


算法描述:用while结构重复画圈操作,每个周期上下左右各一条边,每条边有层数-1个数字。至于对角线和,由于你存在数组里,SUM(a[i,i])+SUM(a[i,n-i+1)-交点值就是答案了(就这么完了~~)



Program surround;
Var
	a:array[1..110,1..110]of longint;
	i,j,x,y,n:longint;
	tota,total:longint;
	aa:array[1..110,1..110]of boolean;
	
Begin
	readln(n);
	tota:=0;
	total:=n*n;
	i:=(n div 2)+1;
	x:=i;
	y:=i;
	fillchar(aa,sizeof(aa),false);
	inc(tota);
	aa[x,y]:=true;
	a[x,y]:=tota;
	while tota<>total do
		begin
			inc(tota);
			inc(x);
			aa[x,y]:=true;
			a[x,y]:=tota;
			while aa[x-1,y] do
				begin
					inc(tota);
					dec(y);
					aa[x,y]:=true;
					a[x,y]:=tota;
				end;
			while aa[x,y+1] do
				begin
					inc(tota);
					dec(x);
					aa[x,y]:=true;
					a[x,y]:=tota;
				end;
			while aa[x+1,y] do
				begin
					inc(tota);
					inc(y);
					aa[x,y]:=true;
					a[x,y]:=tota;
				end;
			while aa[x,y-1] do
				begin
					inc(tota);
					inc(x);
					aa[x,y]:=true;
					a[x,y]:=tota;
				end;
			begin
			aa[x,y]:=false;
			a[x,y]:=0;
			dec(tota);
			dec(x);
			end;
		end;
	total:=0;
	for i:=1 to n do
		inc(total,a[i,i]+a[i,n-i+1]);
	for i:=1 to n do
	begin
		for j:=1 to n do
			write(a[j,i],' ');
		writeln;
	end;
	writeln(total-a[(n div 2)+1,(n div 2)+1]);
End.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值