AC Java solution


  • 0
    Y
    public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        if(n < 1) return result;
        int h = 0, v = 0;
        int num = 1;
        int i = 0, j = 0;
        while(num <= n*n)
        {
            for(i = h; i < n - h; i++)
                result[j][i] = num++;
            i--;
            for(j = v + 1; j < n - v; j++)
                result[j][i] = num++;
            j--;
            for(i = n - h - 2; i >= h; i--)
                result[j][i] = num++;
            i++;
            for(j = n - v - 2; j >= h + 1; j--)
               result[j][i] = num++;
            j++;
            h = h + 1;
            v = v + 1;
        }
        return result;
    }
    

    }


  • 0
    J

    what do 'I, j, h, v' stand for? Would you name them better understandable?


  • 0
    Y

    Thank you for your advice.
    Think our matrix like a m*n matrix and where m = n,
    then j is the position of an element in m, and i is the position of an element in n.
    The h stands for the steps that i moves, which means the moves in horizontal direction, and v stands for the steps that j moves, which means the moves in vertical direction.
    I think a diagram will explain better, but I can't draw one here, hope my explanation is understandable.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.