这题除了循环条件难想,逻辑复杂,调试麻烦之外还是不错的;按照剑指offer的思路,循环打印都ok,唯独那个columns>start*2我是想不到的-0-,先上java代码:
import java.util.ArrayList;
public class Solution {
ArrayList<Integer> list = new ArrayList<>();
public ArrayList<Integer> printMatrix(int [][] matrix) {
if(matrix == null){
return null;
}
int start = 0;
int rows = matrix.length;
int columns = matrix[0].length;
while((columns > start * 2)&&(rows > start * 2)){
this.Print(matrix,rows,columns,start);
start++;
}return list;
}
public void Print(int[][] numbers,int rows,int columns,int start){
for(int i = start;i<columns-start;i++ ){
list.add(numbers[start][i]);
}
for(int i = start+1; i < rows - start;i++){
list.add(numbers[i][columns - start - 1]);
}
for(int i = columns - start - 2;i>= start&& rows - start - 1 > start;i--){
list.add(numbers[rows-start-1][i]);
}
for(int i = rows - start - 2;i>start&& columns - start - 1 > start;i--){
list.add(numbers[i][start]);
}
}
}
然而我很喜欢python的旋转解法,好想,好用:
# -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
result = []
while matrix:
result += matrix.pop(0)
if matrix:
matrix = self.reverse_matrix(matrix)
return result
def reverse_matrix(self,matrix):
row = len(matrix)
col = len(matrix[0])
new_matrix = []
for i in range(col):
new_line = []
for j in range(row):
new_line.append(matrix[j][col-i-1])
new_matrix.append(new_line)
return new_matrix