[Array] Print matrix from outside to inside

Posted by |Adam| on Thu, 07 Nov 2019 21:46:43 +0100

Tag: Array

Title Description

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

Solving problems

First get the number of rows and columns of the matrix, and then rotate the printed data one by one. After one rotation, go forward and backward one unit diagonally, respectively.
Note the case of single rows and columns.

  • Be careful
    1. Determine whether the condition should be equal sign
    2. Loop End Conditions
    3. Where to place a list of rows or a single number
Reference Code
import java.util.ArrayList;
public class PrintMatrix {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        
        //Not a square matrix, rows and columns are calculated separately
        int row = matrix.length;
        int col = matrix[0].length;
        //Send blank
        ArrayList<Integer> res = new ArrayList<>();
        if(row==0 && col==0)
            return res;
        //
        int left = 0, right = col - 1;
        int top = 0, bottom = row - 1;
        while(left <= right && top <= bottom){
            //Left to Right
            for(int i=left; i<=right; i++)
                res.add(matrix[top][i]);
            //top to bottom
            for(int j=top+1; j<=bottom; j++ )
                res.add(matrix[j][right]);
            
            //Bottom to top to determine if it is a single line
            if(top != bottom){
            	for(int i= right-1; i>=left; i--)
            		res.add(matrix[bottom][i]);
            }           
            //Right to left to determine if it is a single column
            if(left != right){
                for(int j=bottom-1; j>top; j--)
                	res.add(matrix[j][left]);
            }
        
            left++;
            right--;
            top++;
            bottom--;          
        }    
        return res;
    }
    public static void main(String[] args) {
		PrintMatrix p = new PrintMatrix();
		int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
		ArrayList<Integer> result = new ArrayList<>();
		result = p.printMatrix(matrix);
		for(int i: result)
			System.out.print(i);
	}
}

Topics: Programming Java