输出指定格式的数字矩阵

输出样例:

1 2 6 7 15 16 28 29 3 5 8 14 17 27 30 43 4 9 13 18 26 31 42 44 10 12 19 25 32 41 45 54 11 20 24 33 40 46 53 55 21 23 34 39 47 52 56 61 22 35 38 48 51 57 60 62 36 37 49 50 58 59 63 64

解题思路:

1. 每个点必然存在于一条45度的斜线上, 比如5存在于4, 5, 6组成的斜线。

2. 这条斜线之前是一个正方形的一半

3. 为(1),(2, 3),(4, 5, 6),(7, 8, 9, 10)......这些斜线编号为0, 1, 2, 3, 4, 则奇数编号的是从上向下排列, 偶数编号的是从下向上排列,因此对奇数斜线而言, 每个坐标点是该斜线上的第y坐标个点, 反之则是第x坐标个点

4. 通过1, 2可知斜线之前已有的数字个数, 通过3可以知道该点是斜线的第N个,因此, 可以求得每个点应该显示的数字。

Python版代码

#!/usr/bin/python #--coding: utf-8-- #author: selfimpr #blog: http://blog.youkuaiyun.com/lgg201 #mail: lgg860911@yahoo.com.cn #求边长为n的正方形一半面积(包含中间的斜边部分) def half_area(n): return (pow(n, 2) - n) / 2 + n #获取指定坐标以及最大列数时该点所在斜线之前部分面积 def pre_area(x, y, n): return half_area(x + y) if x + y < n else (pow(n, 2) - half_area(2 * (n - 1) - x - y + 1)) #获取指定坐标以及最大列数时该点在所在斜线上按该斜线排列顺序是第几个点 def pre_line(x, y, n): return (x if x + y < n else n - y - 1) if (x + y) % 2 == 0 else (y if x + y < n else n - x - 1) #根据给定的n打印数字矩阵 def f(n): y = 0 while y < n: x = 0 while x < n: print "%5d" % (pre_area(x, y, n) + pre_line(x, y, n) + 1), x += 1 y += 1 print print f(15)

标准C代码

#include <stdio.h> /** * @author: selfimpr * @blog: http://blog.youkuaiyun.com/lgg201 * @mail: lgg860911@yahoo.com.cn */ int half_area(int n); int pre_area(int x, int y, int n); int pre_line(int x, int y, int n); int main() { int n, x, y; printf("Please input n:"); scanf("%d", &n); y = 0; while(y < n) { x = 0; while(x < n) { printf("%5d", (pre_area(x, y, n) + pre_line(x, y, n) + 1)); x ++; } y ++; printf("/n/n"); } } int half_area(int n) { return n * (n - 1) / 2 + n; } int pre_area(int x, int y, int n) { return (x + y < n) ? half_area(x + y) : (n * n - half_area(2 * (n - 1) - x - y + 1)); } int pre_line(int x, int y, int n) { return ((x + y) % 2 == 0) ? ((x + y < n) ? x : (n - y - 1)) : ((x + y < n) ? y : (n - x - 1)); }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值