The sword refers to Offer-Java-Print Matrix Clockwise

print matrix clockwise


Question:
Input a matrix and print each number in clockwise order from outside to inside. For example, if you enter the following 4 X 4 matrix: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 then Print out the numbers 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
Code:

package com.sjsq.test;

/**
 * @author shuijianshiqing
 * @date 2020/5/21 22:43
 */

/**
 * 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,
 * 例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
 * 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
 */

import java.util.ArrayList;
public class Solution {
    
    
    public ArrayList<Integer> printMatrix(int [][] matrix) {
    
    

        ArrayList<Integer> list = new ArrayList<>();
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
    
    
            return list;
        }
        int up = 0;
        int down = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;
        while(true){
    
    
            // 最上面一行
            for(int col = left;col <= right;col++){
    
    
                list.add(matrix[up][col]);
            }
            // 向下逼近
            up++;
            if(up > down){
    
    
                break;
            }
            // 最右边一行
            for(int row=up;row<=down;row++){
    
    
                list.add(matrix[row][right]);
            }
            // 向左逼近
            right--;
            if(left>right){
    
    
                break;
            }
            // 最下边一行
            for(int col=right;col>=left;col--){
    
    
                list.add(matrix[down][col]);
            }
            // 向上逼近
            down--;
            if(up>down){
    
    
                break;
            }
            // 最左边一行
            for(int row=down;row>=up;row--){
    
    
                list.add(matrix[row][left]);
            }
            // 向右逼近
            left++;
            if(left>right){
    
    
                break;
            }
        }
        return list;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324175478&siteId=291194637