leetcode 59 Spiral Matrix II ------ java

Posted xiaoba1203

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 59 Spiral Matrix II ------ 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 ]
]

 这道题其实就是第54题Spiral Matrix的输入和输出反过来而已。

很简单,一圈一圈往里写数据,circle 共有n/2+1圈。然后写入数据即可。

public class Solution {
    public int[][] generateMatrix(int n) {
        int[][]    result = new int[n][n];
        int num = n/2+1;
        int left = 0,right = n-1;
        int ans = 1;
        for ( int circle = 0;circle < num;circle++){
            for( int i = left;i<=right;i++){
                result[circle][i] = ans;
                ans++;
            }
            for( int i = left+1;i<=right;i++){
                result[i][n-1-circle] = ans;
                ans++;
            }
            for( int i =right-1;i>=left;i--){
                result[n-circle-1][i] = ans;
                ans++;
            }
            for( int i = right-1;i>left;i--){
                result[i][circle] = ans;
                ans++;
            }
            left++;
            right--;
        }
     
        return result;
    }
}

 

 

 

以上是关于leetcode 59 Spiral Matrix II ------ java的主要内容,如果未能解决你的问题,请参考以下文章

leetcode59.Spiral Matrix II

[LeetCode]59. Spiral Matrix II

Leetcode59 Spiral Matrix II

[leetcode-59-Spiral Matrix II]

LeetCode59 Spiral Matrix II

LeetCode-59-Spiral Matrix II