59. Spiral Matrix II (Medium)

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

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

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

Hints

Solutions

https://www.programcreek.com/2014/05/leetcode-spiral-matrix-ii-java/

  • Java
class Solution {
    public int[][] generateMatrix(int n) {
        int total = n*n;
        int[][] result= new int[n][n];

        int x=0;
        int y=0;
        int step = 0;

        for(int i=0;i<total;){
            while(y+step<n){
                i++;
                result[x][y]=i; 
                y++;

            }    
            y--;
            x++;

            while(x+step<n){
                i++;
                result[x][y]=i;
                x++;
            }
            x--;
            y--;

            while(y>=0+step){
                i++;
                result[x][y]=i;
                y--;
            }
            y++;
            x--;
            step++;

            while(x>=0+step){
                i++;
                result[x][y]=i;
                x--;
            }
            x++;
            y++;
        }

        return result;
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-08 12:28:51

results matching ""

    No results matching ""