# Title-brushing Notes "Sword Finger offer" - Title 19 Clockwise Printing Matrix

#### Title Description:

Input a matrix and print out each number clockwise from outside to inside.
For example, if the following 4X 4 matrix is input:
1 2 3 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 are printed in turn.

#### Train of thought:

```Thought: Change direction by judging conditions
1. Change direction every time you encounter four corners
2. The direction of transformation is 90 degrees clockwise.
3. Clockwise 90 degrees can be expressed by changing the positive and negative directions.
4. Make the current position px, py, current speed dx, dy,
dx    dy
Right: 10
Down: 0 1
Left: -10
Up: 0-1
5. After changing the direction, the corresponding boundary needs to be reduced by one grid.
```

#### Code

```public class PrintMatrix {

public static void printMatrix(int[][] matrix) {
int top = 0;
int bottom = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
// Initial state
int dx = 1;
int dy = 0;
int x = 0;
int y = 0;

while (top <= bottom && left <= right) {  // Continue while there are still unfinished sequences
// Control direction
if (x == right && y == top && dx == 1 && dy == 0) {
// Encounter the upper right corner and move in the right direction.
dx = 0;
dy = 1;
top += 1;
} else if (x == right && y == bottom && dx == 0 && dy == 1) {
dx = -1;
dy = 0;
right -= 1;
} else if (x == left && y == bottom && dx == -1 && dy == 0) {
dx = 0;
dy = -1;
bottom -= 1;
} else if (x == left && y == top && dx == 0 && dy == -1) {
dx = 1;
dy = 0;
left += 1;
}
// One square at a time in the current direction.
System.out.print(matrix[y][x] + " ");
x += dx;
y += dy;
}
}

public static void main(String[] args) {
int[][] matrix = new int[][]{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};

printMatrix(matrix);
}

}
```
##### According to Feynman's method of learning, what you learn can be consolidated better only when you export it.

Added by Grant Cooper on Wed, 02 Oct 2019 05:42:54 +0300