顺时针打印矩阵

public class PrintMatrix {

public static void main(String[] args) {
  int[][] matrix = {{0,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
  ArrayList<Integer> list = printMatrix(matrix);
  for(Integer i : list){
    System.out.println(i);
  }
}

public static ArrayList<Integer> printMatrix(int[][] matrix) {
  ArrayList<Integer> list = new ArrayList<Integer>();
  int i = 0;
  int j = 0;
  int M = matrix.length;
  int N = matrix[0].length;
  int[][] temp = new int[M][N];
  while (!isFinsh(temp)){
    for(; j < matrix[0].length && temp[i][j] == 0; ++j){
    list.add(matrix[i][j]);
    temp[i][j] = 1;
    }
    --j;
    ++i;
    for(; i < matrix.length&& temp[i][j] == 0; ++i){
      list.add(matrix[i][j]);
      temp[i][j] = 1;
    }
    --i;
    --j;
    for(; j >= 0&& temp[i][j] == 0; --j){
      list.add(matrix[i][j]);
      temp[i][j] = 1;
    }
    ++j;
    --i;
    for(; i >=1&& temp[i][j] == 0; --i){
      list.add(matrix[i][j]);
      temp[i][j] = 1;
    }
    ++i;
    ++j;
  }
  return list;
}
  public static boolean isFinsh(int temp[][]){
    int M = temp.length;
    int N = temp[0].length;
    for(int k=0;k<M;k++){
      for( int l=0;l<N;l++){
        if(temp[k][l] ==0) return false;
      }
    }
    return true;
  }
}

原文地址:https://www.cnblogs.com/huaiyinxiaojiang/p/6605654.html