顺时针打印矩阵
1. 题目形容
输出一个矩阵,依照从内向里以顺时针的程序顺次打印出每一个数字
2. 示例
[[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
则顺次打印出数字 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
3. 解题思路
顺时针走,即向右 -> 向下 -> 向左 -> 向上,一共要走(长 * 宽)步。
遇到边界就改变方向,当向上碰到顶的时候,四个边界都放大。思路简略,一个循环即可!
4. Java 实现
import java.util.ArrayList;
public class Solution {public ArrayList<Integer> printMatrix(int [][] matrix) {ArrayList<Integer> res = new ArrayList();
int rows = matrix.length; // 行的大小
int cols = matrix[0].length; // 列的大小
if (rows == 0 || cols == 0){return res;}
// 从左到右开始遍历,right 最左边【列】,从上到下,bottom 最底部【行】int left = 0, right = cols-1, top = 0, bottom = rows -1;
while(left <= right && top <= bottom){
// 从左到右开始遍历
for(int i = left; i <= right; i++){res.add(matrix[top][i]);
}
// 从上到下开始遍历
for (int i = top+1; i <= bottom; i++){res.add(matrix[i][right]);
}
// 从下往上开始遍历
if (top != bottom){for (int i = right-1; i>= left; i--){res.add(matrix[bottom][i]);
}
}
// 从 右往左开始遍历
if (left != right){for (int i = bottom-1; i > top; i--){res.add(matrix[i][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return res;
}
}
5. Python 实现
# -*- coding:utf-8 -*-
class Solution:
# matrix 类型为二维列表,须要返回列表
def printMatrix(self, matrix):
if matrix == None:
return
rows = len(matrix)
columns = len(matrix[0])
start = 0
while rows > start * 2 and columns > start * 2:
self.PrintMatrixInCircle(matrix, columns, rows, start)
start += 1
print('')
def PrintMatrixInCircle(self, matrix, columns, rows, start):
endX = columns - 1 - start
endY = rows - 1 - start
# 从左到右打印一行
for i in range(start, endX+1):
number = matrix[start][i]
print(number, '', end='')
# 从上到下打印一行
if start < endY:
for i in range(start+1, endY+1):
number = matrix[i][endX]
print(number, '', end='')
# 从右到左打印一行
if start < endX and start < endY:
for i in range(endX-1, start-1, -1):
number = matrix[endY][i]
print(number, '', end='')
# 从下到上打印一行
if start < endX and start < endY-1:
for i in range(endY-1, start, -1):
number = matrix[i][start]
print(number, '', end='')
如果您感觉本文有用,请点个“在看”