Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
原题链接:https://oj.leetcode.com/problems/spiral-matrix-ii/
之前的一题是将螺旋结构的二维数组转成一维数组,此题正好相反,故只需将原来的位置上取下来的元素放回去。
public class SpiralMatrixII { public static void main(String[] args) { int[][] matrix = new SpiralMatrixII().generateMatrix(3); for(int[] r : matrix){ for(int c : r) System.out.print(c + "\t"); System.out.println(); } } public int[][] generateMatrix(int n) { int[][] matrix = new int[n][n]; if(n == 0) return matrix; int l = 0, r = matrix[0].length - 1; int u = 0, d = matrix.length - 1; int num = 1; while (l <= r && u <= d) { for (int i = l; i <= r; i++) matrix[u][i] = num++; u++; if (u > d) continue; for (int i = u; i <= d; i++) matrix[i][r] = num++; r--; if (l > r) continue; for (int i = r; i >= l; i--) matrix[d][i] = num++; d--; if (u > d) continue; for (int i = d; i >= u; i--) matrix[i][l] = num++; l++; } return matrix; } }
时间: 2024-11-07 18:04:42