顺时针打印矩阵
顺时针打印矩阵
http://www.nowcoder.com/questionTerminal/9b4c81a02cd34f76be2659fa0d54342a
顺时针打印矩阵
思路:利用四个边界来控制
import java.util.ArrayList; public class Solution { public ArrayList<Integer> printMatrix(int [][] matrix) { if(matrix.length == 0) return null; ArrayList<Integer> arrayList = new ArrayList<>(); int left=0,right=matrix[0].length-1,up=0,down=matrix.length-1; while(true){ for (int i=left;i<=right;i++) arrayList.add(matrix[up][i]); if(++up>down) break; for (int i=up;i<=down;i++) arrayList.add(matrix[i][right]); if(--right<left) break; for (int i=right;i>=left;i--) arrayList.add(matrix[down][i]); if(--down<up) break; for (int i=down;i>=up;i--) arrayList.add(matrix[i][left]); if(++left>right) break; } return arrayList; } }