你的敘述不是很完全,所以不確定有沒有誤解你的意思…
code: http://pastebin.com/JspsCXCs
% python walk_square.py 5
[[ 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]]
[13 19 18 17 12 7 8 9 14 20 25 24 23 22 21 16 11 6 1 2 3 4 5 10 15]
% python walk_square.py -s 7
[[33 27 30 49 45 13 32]
[41 14 42 31 12 46 9]
[37 39 48 2 3 36 29]
[22 17 47 21 15 24 4]
[19 25 1 34 26 7 16]
[38 43 35 18 10 23 6]
[44 8 40 11 5 20 28]]
[21 48 2 3 15 26 34 1 47 39 14 42 31 12 46 36 24 7 23 10 18 35 43 25 17
37 41 33 27 30 49 45 13 32 9 29 4 16 6 28 20 5 11 40 8 44 38 19 22]
========== >8 walk_square.py >8 ===========
#!/usr/bin/env python
import numpy as np
import argparse
def create_test(size, shuffle=False):
data = np.arange(1, size*size+1)
if shuffle:
np.random.shuffle(data)
return data.reshape(size, size)
def walk(data, size, level):
steps=np.array([[0,1], [1,0], [0,-1], [-1,0]])
walks=steps[np.arange(4).repeat(level*2)]
start=(size - 1) / 2 - level
return [data[tuple(x + (start, start))] for x in walks.cumsum(0)]
def offset(level):
step=(level-1)*2+1
off=[0, 1, step, 1, step, 1, step, 1]
return np.cumsum(off)+(level-1)
def solve(data, size):
result = [data[(size/2, size/2)]]
rect1 = walk(data, size, 1)
off = np.argmax(rect1)
result = np.append(result, np.roll(rect1, -off))
for level in range(2, size/2 + 1):
rect = walk(data, size, level)
tmp = np.roll(rect, -offset(level)[off])
result = np.append(result, tmp)
return result
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Square walker')
parser.add_argument('size', help='size of data')
parser.add_argument('-s', '