螺旋加密笔记

算法详解

螺旋矩阵即一个按顺时针顺序螺旋排序的正方形矩阵,呈现一个螺旋状,故称为螺旋矩阵。

spiral matrix

螺旋式的迭代是算法上的问题,这里给出螺旋迭代的代码:

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
def spiral(row: int, col: int):
"""
顺时针螺旋迭代器,返回一个键值对

Parameters:
row - 矩阵行数
col - 矩阵列数

Returns:
键值对 (i, j)
"""
left, right = 0, col
up, down = 0, row
x, y = 0, 0
while left < right and up < down:
for x in range(left, right):
yield y, x
up += 1
for y in range(up, down):
yield y, x
right -= 1
for x in range(left, right)[::-1]:
yield y, x
down -= 1
for y in range(up, down)[::-1]:
yield y, x
left += 1

def spiralRange(row: int, col: int, start: int = 0):
"""
顺时针螺旋序列生成器

Parameters:
row - 矩阵行数
col - 矩阵列数

Returns:
顺时针螺旋序列
"""
r = [0] * (row * col)
for i, j in spiral(row, col):
r[i * row + j] = start
start += 1
return r


def spiralMat(row: int, col: int):
"""
顺时针螺旋矩阵生成器

Parameters:
row - 矩阵行数
col - 矩阵列数

Returns:
顺时针螺旋矩阵
"""
r = list(spiralRange(row, col))
mat = []
for i in range(row):
mat.append(r[i*col:(i+1)*col])
return mat

加密序列的示例代码:

1
2
3
4
5
6
7
data = 'ohhhhhhf5-410f3f969bl696}6-a-1eb59ge1-4d3{f9af107'
size = len(data)
c = math.isqrt(size)
print(c, c*c, size)
k = [''] * size
for i, j in enumerate(spiralRange(c, c)):
k[j] = data[i]

解密序列的示例代码:

1
2
3
4
5
6
7
data = 'ohhhhhhf5-410f3f969bl696}6-a-1eb59ge1-4d3{f9af107'
size = len(data)
c = math.isqrt(size)
print(c, c*c, size)
k = ''
for i in spiralRange(c, c):
k += data[i]