Source: Spiral Order Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
解題:
- 這種環狀填數的題目並不難,是要先花點時間把每一邊的數字填入規則及迴圈的走向確定下來;
- 另外須注意的是上右下左四邊都有可能單邊迴圈跑完之後數字就填完了,必須另外加個if來判斷是否應跳出迴圈以避免錯誤
(其實也沒什麼好解釋的,code雖然長但也長得很簡單直接看就可以了)
code:
def generateMatrix(self, A):
if A <= 0: return [[]]
elif A == 1: return [[1]]
bot = A – 1
right = A – 1
top = 0
left = 0
output = []
for i in range(A):
output.append([0] * A)
indice = 1
total_indices = A * A
while indice total_indices: break
#right border
for i in range(top, bot + 1):
output[i][right] = indice
indice += 1
right -= 1
if indice > total_indices: break
#bot border
for i in range(right, left – 1, -1):
output[bot][i] = indice
indice += 1
bot -= 1
if indice > total_indices: break
#left border
for i in range(bot, top – 1, -1):
output[i][left] = indice
indice += 1
left += 1
return output
GitHub: GitHub