LeetCode:java轉圈打印矩陣

  public static void main(String[] args) {
      int [] [] arr = {{1,2,3},{4,5,6}};
      sprialOreder(arr);

    }

    public static void sprialOreder(int[] [] matrix) {
        int tR = 0;
        int tC = 0;
        int dR = matrix.length-1;
        int dC = matrix[0].length -1;
        while (tR<=dR && tC<=dC){
            printEdge(matrix,tR++,tC++,dR--,dC--);
        }
    }
    private static void printEdge(int[][] m, int tR, int tC, int dR, int dC) {
        if(tR == dR){//子矩陣只有一行時
            for (int i = tC; i <dC ; i++) {
                System.out.println(m[tR][i] + " ");

            }
        }else if(tC==dC){//子矩陣只有一列時
            for(int i = tR;i<dR;i++){
                System.out.println(m[i][tC]+" ");
            }
        }else {//一般情況
            int curC = tC;
            int curR = tR;
            while (curC!=dC){
                System.out.println(m[tR][curC]+" ");
                curC ++;
            }
            while (curR !=dR){
                System.out.println(m[curR][dC]+" ");
                curR ++;
            }
            while (curC !=tC){
                System.out.println(m[dR][curC]+" ");
                curC--;
            }
            while (curR !=tR){
                System.out.println(m[curR][tC]+" ");
                curR --;
            }
        }

    }
1 
2 
3 
6 
5 
4 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章