您的位置:首页 > 其它

20、顺时针打印矩阵

2017-07-30 17:42 323 查看
LeetCode原题54,复习一遍

import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> ret = new ArrayList<>();
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return ret;
int rowstart = 0, rowend = matrix.length-1;
int colstart = 0, colend = matrix[0].length-1;
while(rowstart <= rowend && colstart <= colend){

for(int i = colstart; i <= colend; i++){
ret.add(matrix[rowstart][i]);
}
rowstart++;
if(rowstart > rowend || colstart > colend) break;

for(int i = rowstart; i <= rowend; i++){
ret.add(matrix[i][colend]);
}
colend--;
if(rowstart > rowend || colstart > colend) break;

for(int i = colend; i >= colstart; i--){
ret.add(matrix[rowend][i]);
}
rowend--;
if(rowstart > rowend || colstart > colend) break;

for(int i = rowend; i >= rowstart; i--){
ret.add(matrix[i][colstart]);
}
colstart++;
if(rowstart > rowend || colstart > colend) break;
}
return ret;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: