Swordfinger offer (Java implementation) clockwise printing matrix

Title Description

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

Solving problems

Print the matrix one by one, in the order shown in the figure.

However, to pay attention to the problem of duplicate printing, two special cases need to be considered.

When printing the bottom, judgment is needed to avoid duplicate printing (for example, when there is only one line element in the matrix, the top has been printed, and the bottom will be duplicated if printing again);

When printing on the left, judgment is needed to avoid duplicate printing (for example, when there is only one column of elements in the matrix, the right side has been printed, and the left side will cause duplication).

code implementation

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

        if (matrix == null) {
            return result;
        }

        int up = 0;
        int down = matrix.length - 1;
        int right = matrix[0].length - 1;
        int left = 0;

        // The outermost layer of each printed matrix
        while (up <= down && right >= left) {
            // Upper side
            for (int i = left; i <= right; i++) {
                result.add(matrix[up][i]);
            }
            // Right
            for (int i = up + 1; i <= down; i++) {
                result.add(matrix[i][right]);
            }
            // Below, but judgment is needed at this point to avoid duplicate printing
            //(For example, when there is only one row of elements in a matrix, the top is printed and the bottom is printed again, which will cause repetition.)
            if (down > up) {
                for (int i = right - 1; i >= left; i--) {
                    result.add(matrix[down][i]);
                }
            }
            // Left, but judgment is needed at this point to avoid duplicate printing
            //(For example, if there is only one column of elements in a matrix, then the right side has been printed, and the left side will be duplicated.)
            if (right > left) {
                for (int i = down - 1; i > up; i--) {
                    result.add(matrix[i][left]);
                }
            }

            // Indent and print the elements in the matrix
            up++;
            down--;
            right--;
            left++;
        }

        return result;
    }
}

Keywords: Java

Added by sanlove on Sun, 06 Oct 2019 16:51:51 +0300