# [leetcode-59]spiral matrixII(java)

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 int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
//init result
for(int i = 0;i<n;i++)
for(int j = 0;j<n;j++)
result[i][j] = 0;

int index = 0;
int num = n*n;
int row = 0,col = -1;
while(index<num){
for(col = col+1;col<n;col++){
if(result[row][col]!=0)
break;
result[row][col] = ++index;
}
col--;
for(row = row+1;row<n;row++){
if(result[row][col]!=0)
break;
result[row][col] = ++index;
}
row--;
for(col = col-1;col>=0;col--){
if(result[row][col] != 0)
break;
result[row][col] = ++index;
}
col++;
for(row = row-1;row>=0;row--){
if(result[row][col] != 0)
break;
result[row][col] = ++index;
}
row++;
}
return result;
}

• 本文已收录于以下专栏：

## 【LeetCode-Java】54. Spiral Matrix+59. Spiral Matrix II

54. Spiral Matrix： 1.原题 链接：https://leetcode.com/problems/spiral-matrix/ Given a matrix of m x n e...

## LeetCode 54/59. Spiral Matrix i, ii

1. 题目描述54 Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix ...

## [LeetCode]59.Spiral Matrix II

【题目】 Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral orde...

## leetcode || 59、 Spiral Matrix II

problem： Given an integer n, generate a square matrix filled with elements from 1 to n2...

## Leetcode59. Spiral Matrix II

59. Spiral Matrix II 1、原题 Given an integer n, generate a square matrix filled with elements from 1...

## 【LEETCODE】59-Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. Fo...

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)