https://www.hackerrank.com/challenges/matrix-rotation-algo

[2, 4, 1, 3]可以表示为：

[0 1 0 0]

[0 0 0 1]

[1 0 0 0]

[0 0 1 0]

 1 import re
2
3 def get2DMatrix(n, m, val):
4     return [[val for j in xrange(m)] for i in xrange(n)]
5
6 def rotate(a, r):
7     # n is guaranteed to be even
8     n = len(a)
9     m = len(a[0])
10     s = getDisplace(n, m)
11     s = displacePow(s, r)
12     b = get2DMatrix(n, m, 0)
13     for i in xrange(n):
14         for j in xrange(m):
15             b[i][j] = a[s[i * m + j] / m][s[i * m + j] % m]
16     return b
17
18 def getDisplace(n, m):
19     s = range(n * m)
20     i = 0
21     while i < n / 2 and i < m / 2:
22         rr = n - 2 * i
23         cc = m - 2 * i
24         for j in xrange(1, rr, 1):
25             #left
26             s[(j + i) * m + i] = (j - 1 + i) * m + i
27         for j in xrange(1, cc, 1):
28             #down
29             s[(rr - 1 + i) * m + (j + i)] = (rr - 1 + i) * m + (j - 1 + i)
30         for j in xrange(rr - 2, -1, -1):
31             #right
32             s[(j + i) * m + (cc - 1 + i)] = (j + 1 + i) * m + (cc - 1 + i)
33         for j in xrange(cc - 2, -1, -1):
34             #top
35             s[i * m + (j + i)] = i * m + (j + 1 + i)
36         i += 1
37     return s
38
39 def multiply(a, b):
40     n = len(a)
41     c = []
42     for i in xrange(n):
43         c.append(a[b[i]])
44     return c
45
46 def displacePow(a, k):
47     if k == 1:
48         return a[:]
49     a2 = displacePow(a, k >> 1)
50     if k & 1:
51         return multiply(multiply(a2, a2), a)
52     else:
53         return multiply(a2, a2)
54
55 if __name__ == '__main__':
56     n, m, r = map(int, re.split('\s+', raw_input().strip()))
57     a = []
58     for i in xrange(n):
59         a.append(map(int, re.split('\s+', raw_input().strip())))
60     a = rotate(a, r)
61     for i in xrange(n):
62         print(' '.join(map(str, a[i])))
63         

posted on 2015-07-31 06:56  zhuli19901106  阅读(428)  评论(0编辑  收藏  举报