# -*- coding: utf-8 -*-
'''
Python程序员面试算法宝典---解题总结: 第4章 数组 4.12 如何对数组旋转
题目:
请实现方法: print_rotate_matrix(intmatrix, int n),该方法
用于将一个n*n的二维数组逆时针旋转45度后打印,例如,下图
显示一个3*3的二维数组及其旋转后屏幕输出的效果
1 2 3
4 5 6
7 8 9
从右上角遍历结果为:
3 2 6 1 5 9 4 8 7
分析:
关键:
1 书上解法
弄清楚沿着对角线遍历,从右上角开始,那么遍历的根本点就在于
假设当前遍历的点为a[i][j],那么下次想遍历的是
a[i+1][j+1],
只不过i,j的值有限制而已
2 我没想到
是因为对于对角线上半部分没想到令
从i=0 j=size - 1开始遍历
做范围限制
参考:
Python程序员面试算法宝典
'''
def rotateArray(array):
if not array:
return
# 遍历对角线上半部分
size = len(array)
j = size - 1
while j > 0:
row = 0
col = j
while col < size:
print array[row][col]
row += 1
col += 1
j -= 1
# 遍历对角线和对角线下半部分
i = 0
j = 0
while i < size:
row = i
col = j
while row < size:
print array[row][col]
row += 1
col += 1
i += 1
def process():
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
rotateArray(array)
if __name__ == "__main__":
process()