[编程题]顺时针打印矩阵-JAVA
顺时针打印矩阵
http://www.nowcoder.com/questionTerminal/9b4c81a02cd34f76be2659fa0d54342a
取数方向是→↓←↑,对应direction的0、1、2、3,当List大小为矩阵元素个数时终止循环,不需要麻烦的条件判断,思路简洁。
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int [][] matrix) {
ArrayList<Integer> res = new ArrayList<>();
int col = matrix.length;
int row = matrix[0].length;
int up = 0;
int down = col - 1;
int left = 0;
int right = row - 1;
int i = 0;
int direction = 0;
int size = col * row;
while(res.size()<size){
if(direction%4==0){
for(i=left;i<=right;i++){
res.add(matrix[up][i]);
}
up++;
}
else if(direction%4==1){
for(i=up;i<=down;i++){
res.add(matrix[i][right]);
}
right--;
}
else if(direction%4==2){
for(i=right;i>=left;i--){
res.add(matrix[down][i]);
}
down--;
}
else{
for(i=down;i>=up;i--){
res.add(matrix[i][left]);
}
left++;
}
direction++;
}
return res;
}
}