[online programming] Print matrix clockwise
[problem 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, then print out the numbers 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10
[Solution & Java implementation]
Idea: first print the periphery (pay attention to row by column), and then shrink the circle.
For a two-dimensional array, row pointer i and column pointer j are required to locate an element, and row1,row2,col1,col2 are required to locate a two-dimensional array.
import java.util.ArrayList; public class Solution { public ArrayList<Integer> printMatrix(int[][] matrix) { int row1 = 0; int row2 = matrix.length - 1; int col1 = 0; int col2 = matrix[0].length - 1; ArrayList<Integer> result = new ArrayList<>(); //Shrinking circle while (row1 <= row2 && col1 <= col2) { result.addAll(printBoundary(matrix, row1, row2, col1, col2)); row1++; row2--; col1++; col2--; } return result; } /** *Print a circle */ public ArrayList<Integer> printBoundary(int[][] matrix, int row1, int row2, int col1, int col2) { ArrayList<Integer> list = new ArrayList<>(); //If it's a line if (row1 == row2) { for (int j = col1; j <= col2; j++) { list.add(matrix[row1][j]); } } else if (col1 == col2) { for (int i = row1; i <= row2; i++) { list.add(matrix[i][col2]); } } else { for (int j = col1; j <= col2; j++) { list.add(matrix[row1][j]); } for (int i = row1 + 1; i <= row2; i++) { list.add(matrix[i][col2]); } for (int j = col2 - 1; j >= col1; j--) { list.add(matrix[row2][j]); } for (int i = row2 - 1; i > col1; i--) { list.add(matrix[i][col1]); } } return list; } }