Problem illustration:
given a n*n matrix, print its transition, for example , 90 degree
clockwise,using only constant additional space
analysis:
using O(n^2) space is common,but for constant assistant space, we need to
adopt constant space
solution:
use in place replacement,
take
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
for example
the expected output is
21 16 11 6 1
22 17 12 7 2
23 18 13 8 3
24
19 14 9 4
25 20 15 10 5
after transition,value (0,0) is expected to be transferred to
pos(0,4),while(0,4)→(4,4),(4,4) to (4,0),(4,0)to (0,0),which is the same with
our
so this four elements are called a cycle(for more clear explanation, please
refer to situ permutation)
two keypoints:
1.with the same example,since we use (0,0) to cover (4,0),then the original
value at (4,0) must be stored before coverage or the whole cycle will be
initialized
to the cycle header
2.edge condition handling
source code for above example:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
|
InPlace Transition of a matrix,布布扣,bubuko.com