[leetcode]59. Spiral Matrix II(Java)

来源:互联网 发布:tomcat 域名绑定 端口 编辑:程序博客网 时间:2024/06/05 03:54

https://leetcode.com/problems/spiral-matrix-ii/#/description

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 ]]

package go.jacob.day627;public class Demo2 {/* * Runtime: 2 ms.Your runtime beats 66.13 % of java submissions. */public int[][] generateMatrix(int n) {int[][] res = new int[n][n];if (n < 1)return res;int index = 1, rowStart = 0, rowEnd = n - 1, colStart = 0, colEnd = n - 1;while (index <= n * n) {for (int i = colStart; i <= colEnd; i++) {res[rowStart][i] = index++;}for (int i = rowStart + 1; i <= rowEnd; i++) {res[i][colEnd] = index++;}for (int i = colEnd - 1; i >= colStart; i--) {res[rowEnd][i] = index++;}for (int i = rowEnd - 1; i > rowStart; i--) {res[i][colStart] = index++;}rowStart += 1;rowEnd -= 1;colStart += 1;colEnd -= 1;}return res;}}