Sword finger Offer (19): print matrix clockwise

I. Title Description

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

II. Solutions

The matrix is stored in a two-dimensional array, from left to right, from top to bottom, from right to left, and finally from bottom to top.

For example: first from left to right, print 1, 2, 3, 4
01.02.03.04
05 06 07 08
09 10 11 12
13 14 15 16
From top to bottom, print 8, 12, 16
01.02.03.04
05 06 07 08
09 10 11 12
13 14 15 16
From right to left, print 15, 14, 13
01.02.03.04
05 06 07 08
09 10 11 12
13 14 15 16
Last from bottom to top, print 9, 5
01.02.03.04
05 06 07 08
09 10 11 12
13 14 15 16
This is a cycle

III. programming implementation

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int[][] matrix) {
        ArrayList<Integer> list = new ArrayList<>();
        if (matrix == null || matrix.length == 0) {
            return list;
        }
        printCircle(matrix, 0, matrix.length - 1, 0, matrix[0].length - 1, list);
        return list;
    }

    private void printCircle(int[][] matrix, int startRow, int endRow, int startCol, int endCol, ArrayList<Integer> list) {
        if (startRow < endRow && startCol < endCol) {
            // From left to right
            for (int j = startCol; j <= endCol; j++) {
                list.add(matrix[startRow][j]);
            }
            // From top to bottom
            for (int i = startRow + 1; i <= endRow - 1; i++) {
                list.add(matrix[i][endCol]);
            }
            // From right to left
            for (int j = endCol; j >= startCol; j--) {
                list.add(matrix[endRow][j]);
            }
            // From bottom to top
            for (int i = endRow - 1; i >= startRow + 1; i--) {
                list.add(matrix[i][startCol]);
            }
            // One circle in the cycle
            printCircle(matrix, startRow + 1, endRow - 1, startCol + 1, endCol - 1, list);
        } else if (startRow == endRow && startCol < endCol) {
            // If there is only one line left, turn left to right
            for (int j = startCol; j <= endCol; j++) {
                list.add(matrix[startRow][j]);
            }
        } else if (startRow < endRow && startCol == endCol) {
            // If there is only one column left, top to bottom
            for (int i = startRow; i <= endRow; i++) {
                list.add(matrix[i][startCol]);
            }
        } else if (startRow == endRow && startCol == endCol) {
            // If there is only one left, add the element
            list.add(matrix[startRow][startCol]);
        } else {
            return;
        }
    }
}

Tags: Programming Java

Posted on Tue, 03 Dec 2019 04:17:08 -0800 by slough