[LeetCode 59] Spiral Matrix II

题目链接:spiral-matrix-ii

/** * 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 ]] * */public class SpiralMatrixII {//21 / 21 test cases passed.//Status: Accepted//Runtime: 208 ms//Submitted: 0 minutes agopublic int[][] generateMatrix(int n) {int[][] matrix = new int[n][n];//up// leftright//downint left = 0;int right = n – 1;int up = 0;int down = n – 1;int count = 0;while(left <= right && up <= down) {for(int i = left; i <= right; i ++) {matrix[up][i] = (++ count);}up ++;for(int i = up; i <= down; i ++) {matrix[i][right] = (++count);}right –;for(int i = right; i >= left && up <= down; i –) {matrix[down][i] = (++count);}down –;for(int i = down; i >= up && left <= right; i –) {matrix[i][left] = (++ count);}left ++;}return matrix;}public static void main(String[] args) {}}

,以后我会去到很多很繁华或苍凉,

[LeetCode 59] Spiral Matrix II

相关文章:

你感兴趣的文章:

标签云: