Source: Rotate Matrix
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
You need to do this in place.
Note that if you end up using an additional array, you will only receive partial score.
Example:
If the array is
[
[1, 2],
[3, 4]
]
Then the rotated array becomes:
[
[3, 1],
[4, 2]
]
解題:
- 毫無反應,就只是個旋轉
輸入:
[[0,1,2], [[A[0][0], A[0][1], A[0][2]],
‘[3,4,5], [A[1][0], A[1][1], A[1][2]],
‘[6,7,8]] [A[2][0], A[2][1], A[2][2]]]
輸出:
[[6,3,0], [[A[2][0], A[1][0], A[0][0]],
‘[7,4,1], [A[2][1], A[1][1]. A[0][1]],
‘[8,5,2]] [A[2][2], A[1][2], A[0][2]] - 只需要稍微畫個圖確認一下索引值的變動規律。基本上這題沒什麼難度。
Code:
import copy
class Solution:
# @param A : list of list of integers
# @return the same list modified
def rotate(self, A):
m = len(A)
if m == 0: return A
n = len(A[0])
#simple way
output = copy.deepcopy(A)
cur_col = 0
for i in range(m):
cur_row = m-1
for j in range(n):
output[i][j] = A[cur_row][cur_col]
cur_row -= 1
cur_col += 1
return output
GitHub: GitHub