矩阵找规律题
题目链接:
- 平方矩阵 I
- 平方矩阵 II
- 平方矩阵 III
- 蛇形矩阵
平方矩阵 I
解法一:找坐标规律
while True:x = int(input())if not x:breakfor i in range(x):for j in range(x):print('%d' % min(i + 1, j + 1, x - i, x - j), end = ' ')print()print()
解法二:曼哈顿距离
平方矩阵 ||
解法一:动态规划
while True:x = int(input())if not x:breaka = []for i in range(101):a.append([0]*100)for i in range(x):a[0][i] = i + 1a[i][0] = i + 1for i in range(1, x):for j in range(1, x):a[i][j] = a[i - 1][j - 1]for i in range(x):for j in range(x):print('%d' % a[i][j], end = ' ')print()print()
解法二:找坐标规律
while True:x = int(input())if not x:breakfor i in range(x):for j in range(x):print('%d' % (abs(i - j) + 1), end = ' ')print()print()
平方矩阵 |||
解法一:动态规划
while True:x = int(input())if not x:breaka = []for i in range(101):a.append([0]*15)for i in range(x):a[0][i] = 2 ** ia[i][0] = 2 ** ifor i in range(1, x):for j in range(1, x):a[i][j] = a[i - 1][j - 1] * 4for i in range(x):for j in range(x):print('%d' % a[i][j], end = ' ')print()print()
解法二:找坐标规律
#include <iostream>using namespace std;int main()
{int n;while(cin >> n,n){for(int i = 0; i < n; i ++){for(int j = 0; j < n; j ++)cout << (1 << i) * (1 << j) << ' ';//两个乘数 后者控制基数 1 ~ 2^(n-1) ,前者控制倍数cout << endl;}cout << endl;}return 0;
}
蛇形矩阵
python 题解
a, b = map(int, input().split())
matrix = []
# 初始化列表
for i in range(a):matrix.append([0] * b)# 初始化边界
left, right, top, bottom = 0, b - 1, 0, a - 1
# 填充的数字从1开始
k = 1# 循环运算
while left <= right and top <= bottom:# 从左到右填充上边if top <= bottom:for i in range(left, right + 1):matrix[top][i] = kk += 1top += 1 # 上边界向下缩小# 从上到下填充右边if left <= right:for i in range(top, bottom + 1):matrix[i][right] = k k += 1right -= 1 # 右边界向左缩小# 从右到左填充下边if top <= bottom:for i in range(right, left - 1, -1):matrix[bottom][i] = k k += 1bottom -= 1 # 下边界向上缩小# 从下到上填充左边if left <= right:for i in range(bottom, top - 1, -1):matrix[i][left] = k k += 1left += 1 # 左边界向右缩小for i in range(a):for j in range(b):print("%d" % matrix[i][j], end = ' ')print()