【基础入门题071】螺旋矩阵

x33g5p2x  于2022-01-09 转载在 其他  
字(1.8k)|赞(0)|评价(0)|浏览(291)

【基础入门题】2022.01.06

创建一个m行n列的矩阵,将整数1至m*n从左上角分别以顺时针、逆时针方向螺旋填入矩阵。

如: m,n = 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

逆时针排列:
  1 16 15 14 13 12
  2 17 24 23 22 11
  3 18 19 20 21 10
  4   5   6   7   8   9

编程语言:包括但不限于Python
题目来源:派森特给站每日刷题频道   

输出时用了2种不同方法:

m,n = map(int, input('请输入矩阵的行和列(用空格隔开):').split())

print('\n顺时针排列:')

Array = [[0 for _ in range(n)] for _ in range(m)]
Array[0][0] = 1
i,j,k = 0,0,1

while k<m*n:
    while j+1<n and not Array[i][j+1]:
        j += 1
        k += 1
        Array[i][j] = k
    while i+1<m and not Array[i+1][j]:
        i += 1
        k += 1
        Array[i][j] = k
    while j and not Array[i][j-1]:
        j -= 1
        k += 1
        Array[i][j] = k
    while i and not Array[i-1][j]:
        i -= 1
        k += 1
        Array[i][j] = k

w = len(str(m*n))+1
for a in Array:
    for b in a:
        print(str(b).rjust(w), end='')
    print()

print('\n逆时针排列:')

Array = [[0 for _ in range(n)] for _ in range(m)]
Array[0][0] = 1
i,j,k = 0,0,1

while k<m*n:
    while i+1<m and not Array[i+1][j]:
        i += 1
        k += 1
        Array[i][j] = k
    while j+1<n and not Array[i][j+1]:
        j += 1
        k += 1
        Array[i][j] = k
    while i and not Array[i-1][j]:
        i -= 1
        k += 1
        Array[i][j] = k
    while j and not Array[i][j-1]:
        j -= 1
        k += 1
        Array[i][j] = k
        
#w = len(str(m*n))+1
for a in Array:
    for b in a:
        print(f'{b:>{w}}', end='')
    print()

C语言代码:

#include<stdio.h>  
int main()
{  
    int m,n,x=0,y=0,c=1;
    scanf("%d %d",&m,&n); 
    int a[m+1][n+1]={0},b[m+1][n+1]={0};
    a[0][0]=1;b[0][0]=1;
    printf("顺时针排列:\n");
	while(c!=m*n){   
		while(y+1<n&&!a[x][y+1]) a[x][++y]=++c;
		while(x+1<m&&!a[x+1][y]) a[++x][y]=++c;
		while(y&&!a[x][y-1]) a[x][--y]=++c;
		while(x&&!a[x-1][y]) a[--x][y]=++c;	
	}
	for(x=0;x<m;x++){
		for(y=0;y<n;y++)
	   		printf("%3d", a[x][y]);
	   	printf("\n");
	}
    x=0;y=0;c=1;
    printf("逆时针排列:\n");
	while(c!=m*n){
		while(x+1<m&&!b[x+1][y]) b[++x][y]=++c;
		while(y+1<n&&!b[x][y+1]) b[x][++y]=++c;
		while(x&&!b[x-1][y]) b[--x][y]=++c;	
		while(y&&!b[x][y-1]) b[x][--y]=++c;
	}
	for(x=0;x<m;x++){
		for(y=0;y<n;y++)
	   		printf("%3d", b[x][y]);
	   	printf("\n");
	}
}

相关文章