Realization of Circle Printing Matrix Algorithm by java

  • 2021-07-01 07:29:12
  • OfStack

In this paper, we share the specific code of java to realize circle printing matrix for your reference. The specific contents are as follows

Given 1 Shaping Matrix Matrix, enter (print) element values in a clockwise circle.

For example:

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

The output is: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

Requirement: Extra space complexity is O (1)

The JAVA code is as follows:


package com.bean.algorithmexec;

public class MatrixDemo {

 /*
  *  Given 1 Shaping matrix Matrix Enter (print) the element value in a clockwise circle. 
  *  For example: 
  * 1 2 3 4
  * 5 6 7 8
  * 9 10 11 12
  * 13 14 15 16
  *  The output is: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
  * 
  *  Requirements: Extra space complexity is O ( 1 ) 
  * */

 public static void main(String[] args) {
  // TODO Auto-generated method stub

  // Initialization 1 A  4*4 The shaping matrix of, from the first 1 Line number 1 Column from left to right, 2 Line, number 3 Line, until the first 4 Row assignment in turn  1,2,...16.
  int[][] matrixDemo=new int[4][4];
  matrixDemo=createMatrix();
  printMatrix(matrixDemo);

  // Circular printing 
  spiralOrderPrint(matrixDemo);

 }

 private static int[][] createMatrix() {
  // TODO Auto-generated method stub
  int matrix[][]=new int[4][4];
  int k=1;
  for(int i=0;i<4;i++) {
   for(int j=0;j<4;j++) {
    matrix[i][j]=k;
    k++;
   }
  }

  return matrix;
 }

 // Sequential printing of matrix elements 
 private static void printMatrix(int[][] matrix) {
  for(int i=0;i<4;i++) {
   for(int j=0;j<4;j++) {
    System.out.print(matrix[i][j]+"\t");
   }
   System.out.println();
  }

 }

 // Circular printing 
 private static void spiralOrderPrint(int[][] matrix) {
  int tR=0;
  int tC=0;
  int dR=matrix.length-1;
  int dC=matrix[0].length-1;
  while(tR<=dR && tC<=dC) {
   printEdge(matrix, tR++, tC++, dR--,dC--);
  }
 }

 private static void printEdge(int[][] matrix, int tR, int tC, int dR, int dC) {
  // TODO Auto-generated method stub
  if(tR==dR) {
   // Submatrix only 1 Row time 
   for(int i=tC;i<=dC;i++) {
   System.out.print(matrix[tR][i]+" ");
   }

  }else if(tC==dC) {
   // Submatrix only 1 Column time 
   for(int i=tR;i<=dR;i++){
    System.out.print(matrix[i][tC]+" ");
   }

  }else {
   //1 General situation 
   int curC=tC;
   int curR=tR;
   while(curC!= dC) {
    System.out.print(matrix[tR][curC]+" ");
    curC++;
   }

   while(curR!= dR) {
    System.out.print(matrix[curR][dC]+" ");
    curR++;
   }

   while(curC!= tC) {
    System.out.print(matrix[dR][curC]+" ");
    curC--;
   }

   while(curR!= tR) {
    System.out.print(matrix[curR][tC]+" ");
    curR--;
   }
  }
 }


}

Related articles: