Accepted java solution


  • 0
    T
    class Solution {
        public int[][] generateMatrix(int n) {
            int[][] matrix = new int[n][n];
            int value = 1;
            int i = 0, j = -1;
            int in = 0, jn = 0;
            int num = n;
            int index = 0;
            while(value <= n * n) {
                switch(index) {
                        case 0: { in = 0; jn = 1; break; }
                        case 1: { in = 1; jn = 0; num--; break; }
                        case 2: { in = 0; jn = -1; break; }
                        case 3: { in = -1; jn = 0; num--; break; }
                }
                for(int k = 0; k < num; k++) {
                    i += in;
                    j += jn;
                    matrix[i][j] = value;
                    value++;
                }
                index = (index + 1) % 4;
            }
            return matrix;
        }
    }
    

Log in to reply
 

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