This article describes the method of implementing output loopback numbers (spiral matrix) in Java. Share it for your reference, as follows:
I've seen it before, but I haven't made it; I saw you goodbye to the forum that day, and the inspiration came. It's so amazing
The complexity seems to be o(n)
Save it
package demo;public class snakeMatrixDemo { public static void main(String[] args) { int m = 5;/* row*/ int n = 5;/* column*/ int[][] pos = new int[m][n];/* position*/ /** * The position structure is as follows: [0][0],[0][1],[0][1],[0][2],[0][3],[0][4] * * [1][0],[1][1],[1][2],[1][3],[1][4] * * [2][0],[2][1],[2][2][3],[2][4] * * [3][0],[3][1],[3][2],[3][3][4] * * [4][0],[4][1],[4][2],[4][3],[4][4] */ int count = 0; int r = 0, c = 0;/* r:Line subscript c:Column subscript pos[r][c] corresponds to the above positions*/ /* Assign the direction, first c++, then down r++, then left c--, then up r-- */ final int up = 1; final int down = -1; final int left = 2; final int right = -2; int dir = right;/* Start direction*/ int cir = 1;/* How many rounds of assignment*/ while (count < m * n) { count++; pos[r][c] = count;/* Assignment*/ switch (dir) { case right: if (c < n - cir) {/* There is still no assignment on the right side of the current line*/ c++; } else { dir = down; r++; } break; case down: if (r < m - cir) {/* There is still no assignment below the current column*/ r++; } else { dir = left; c--; } break; case left: if (c > cir - 1) {/* There is still no assignment on the left side of the current line*/ c--; } else { dir = up; r--; } break; case up: if (r > cir) {/* There is no assignment in the current column*/ r--; } else { cir++;/* Assign a circle*/ dir = right; c++; } break; } } System.out.println("Wulin.com test result: "); /* Output */ for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (pos[i][j] < 10) { System.out.print(pos[i][j] + " " + " "); } else { System.out.print(pos[i][j] + " "); } } System.out.println(); } }}Running results:
For more information about Java algorithms, readers who are interested in this site can view the topics: "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation DOM Node Tips", "Summary of Java File and Directory Operation Tips" and "Summary of Java Cache Operation Tips"
I hope this article will be helpful to everyone's Java programming.