题目链接:
思路:
想想矩阵的四周有四堵墙,每读完一层,相应的墙就加一,然后代码实现就好
需要注意的点:极端情况需要另作考虑
算法源码:
package niuke; import java.util.ArrayList; public class 顺时针打印矩阵 { public static ArrayList<Integer> printMatrix(int [][] matrix) { ArrayList<Integer> res = new ArrayList<>(); int length_top = matrix.length; int width_right = matrix[0].length; if(length_top == 1&&width_right==1){ res.add(matrix[0][0]); return res; } int top =0; int right = width_right-1; int bottom = length_top-1; int left = 0; while(left<=right&&top<=bottom){ for(int i = left;i<=right;++i){ res.add(matrix[top][i]); } top++; for(int i = top;i<=bottom;++i){ res.add(matrix[i][right]); } right--; if(top<=bottom) for(int i = right;i>=left;--i){ res.add(matrix[bottom][i]); } bottom--; if(left<=right) for(int i = bottom;i>=top;--i){ res.add(matrix[i][left]); } left++; } // if(matrix.length%2==1){ // res.add(matrix[(matrix.length-1)/2][(matrix.length-1)/2]); // } return res; } public static void main(String[] args) { int n =1; int[][] test = new int[5][5]; for(int i = 0;i<5;++i){ for(int j = 0;j<5;++j){ test[i][j] = n++; } } int[][] test2 = {{1},{2},{3},{4},{5}}; int[][] test3 = {{1,2,3,4,5},{1,2,3,4,5}}; ArrayList<Integer> res = printMatrix(test3); for(Integer each:res){ System.out.println(each); } } }
代码已经ac
希望对大家有所帮助
以上