Python蛇形方阵的实现
作者:机器学习Zero
本文主要介绍了Python蛇形方阵的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
输入:数字m mm,n nn
输出:m mm行n nn列的数字蛇形方阵
1. 从方阵最左上角开始,顺时针向内填充。
初始化一个m mm行n nn列的矩阵matrix,所有元素都为0;然后从第一个位置开始,按顺序填充数字,填满了一列或一行后,就转向填写下一列或下一行,最后打印出这个数字蛇形方阵。代码如下:
def print_snake_matrix(m, n): matrix = [[0]*n for i in range(m)] num = 1 i, j = 0, 0 while num <= m*n: while j < n and matrix[i][j] == 0: matrix[i][j] = num num += 1 j += 1 j -= 1 i += 1 while i < m and matrix[i][j] == 0: matrix[i][j] = num num += 1 i += 1 i -= 1 j -= 1 while j >= 0 and matrix[i][j] == 0: matrix[i][j] = num num += 1 j -= 1 j += 1 i -= 1 while i >= 0 and matrix[i][j] == 0: matrix[i][j] = num num += 1 i -= 1 i += 1 j += 1 for row in matrix: for num in row: print(num, end='\t') print()
执行
print_snake_matrix(4, 6)
输出
1 2 3 4 5 6
16 17 18 19 20 7
15 24 23 22 21 8
14 13 12 11 10 9
c++实现
#include <iostream> #include <vector> using namespace std; void print_snake_matrix(int m, int n) { vector<vector<int>> matrix(m, vector<int>(n, 0)); int num = 1; int i = 0, j = 0; while (num <= m * n) { while (j < n && matrix[i][j] == 0) { matrix[i][j] = num; num++; j++; } j--; i++; while (i < m && matrix[i][j] == 0) { matrix[i][j] = num; num++; i++; } i--; j--; while (j >= 0 && matrix[i][j] == 0) { matrix[i][j] = num; num++; j--; } j++; i--; while (i >= 0 && matrix[i][j] == 0) { matrix[i][j] = num; num++; i--; } i++; j++; } for (auto row : matrix) { for (int num : row) { cout << num << "\t"; } cout << endl; } }
2. 从方阵最右上角开始,逆时针向内填充。
由于是从右上角开始填充,所以初始位置为第0 00行第n − 1 n-1n−1列。随后的填充顺序也需要逆时针旋转,以保证填充的数字顺序正确。除此之外,这段代码的实现与前面的代码基本相同,都是采用四个while循环来按顺序填充数字。代码如下:
def print_snake_matrix(m, n): matrix = [[0]*n for i in range(m)] num = 1 i, j = 0, n-1 while num <= m*n: while j >= 0 and matrix[i][j] == 0: matrix[i][j] = num num += 1 j -= 1 j += 1 i += 1 while i < m and matrix[i][j] == 0: matrix[i][j] = num num += 1 i += 1 i -= 1 j += 1 while j < n and matrix[i][j] == 0: matrix[i][j] = num num += 1 j += 1 j -= 1 i -= 1 while i >= 0 and matrix[i][j] == 0: matrix[i][j] = num num += 1 i -= 1 i += 1 j -= 1 for row in matrix: for num in row: print(num, end='\t') print()
执行
print_snake_matrix(4, 6)
输出
6 5 4 3 2 1
7 20 19 18 17 16
8 21 22 23 24 15
9 10 11 12 13 14
c++实现
void print_snake_matrix(int m, int n) { vector<vector<int>> matrix(m, vector<int>(n, 0)); int num = 1; int i = 0, j = n - 1; while (num <= m * n) { while (j >= 0 && matrix[i][j] == 0) { matrix[i][j] = num; num++; j--; } j++; i++; while (i < m && matrix[i][j] == 0) { matrix[i][j] = num; num++; i++; } i--; j++; while (j < n && matrix[i][j] == 0) { matrix[i][j] = num; num++; j++; } j--; i--; while (i >= 0 && matrix[i][j] == 0) { matrix[i][j] = num; num++; i--; } i++; j--; } for (auto row : matrix) { for (int num : row) { cout << num << "\t"; } cout << endl; } }
到此这篇关于Python蛇形方阵的实现的文章就介绍到这了,更多相关Python蛇形方阵内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!