题目:
1 A B C D E F G H
2 V W X Y Z A B I
3 U J K L M N C J
4 T I H G F E D K
5 S R Q P O N M L
输入:一行字符串,包含两个M,N,M和N均为大于0,小于10000的整数,M代表行,N代表列。
输出:M*N的矩阵,以空格分隔。
题目解析:
在这个矩阵中,是按照顺时针填入字母(右->下->左->上->右->下->......)
因此,首先想到了顺时针打印矩阵,其次将字母输入进位置。
代码:j
class Solution:
def huihuanzimu(self, M, N):
left, right, top, bottom = 0, N-1, 0, M-1
matrix = [[0] * N for i in range(M)]
x = 'A'
count = 0
while left <= right and top <= bottom:
for row in range(left, right):
matrix[top][row] = x
x = chr(ord(x) + 1)
count += 1
if count >= 26:
x = 'A'
count = 0
print(count)
print(matrix[top][row])
for col in range(top, bottom):
matrix[col][right] = x
x = chr(ord(x) + 1)
count += 1
if count >= 26:
x = 'A'
count = 0
#if left < right and top < bottom:
for row in range(right, left, -1):
matrix[bottom][row] = x
x = chr(ord(x) + 1)
count += 1
if count >= 26:
x = 'A'
count = 0
for col in range(bottom, top, -1):
matrix[col][left] = x
x = chr(ord(x) + 1)
count += 1
if count >= 26:
x = 'A'
count = 0
left += 1
right -= 1
top += 1
bottom -= 1
for i in range(M):
for j in range(N):
print(matrix[i][j], end = " ")
print()
solution = Solution()
solution.huihuanzimu(10,8)
结果:
代码遇到的问题:
1.如何顺时针打印矩阵?
答:采用四个指针,分别记录上下左右。
2.如何创建python二维数组?
答: matrix = [[false] * N for i in range(M)]
对于[[false] * N] * M 改变第一个的数的时候,也会将其他同时改变。
3.如何打印英文字母?
答:ASCII码:‘A’:65,‘a’:97。
chr():将数字转化为字母。
ord():将字母转化为数字。
本题中,还需注意到超出后,需要再从A开始。
如果大家有更好的解决方法,希望和大家共同探讨!