# Java for Leetcode 059 Spiral Matrix II

Source: Internet
Author: User

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

Problem Solving Ideas:

Refer to Java for Leetcode 054 Spiral Matrix, modify the following code, Java implementation is as follows:

`static public int[][] Generatematrix (int n) {        if (n==0)            return new int[0][0];    Int[][] Matrix=new int[n][n];    int num=0,left = 0, right = matrix[0].length-1, up = 0, down = matrix.length-1;        while (left <= right && up <= down) {for            (int i = left; I <= right&&up<=down; i++)                ma Trix[up][i]=++num;            up++;            for (int i = up; I <= down&&left<=right; i++)                matrix[i][right]=++num;            right--;            for (int i = right; I >= left&&up<=down; i--)                matrix[down][i]=++num;            down--;            for (int i = down; I >= up&&left<=right; i--)                matrix[i][left]=++num;            left++;        }    return matrix;      }`

Java for Leetcode 059 Spiral Matrix II

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.