My AC solution using direction variable (JAVA)


  • 0
    J
    public int[][] generateMatrix(int n) {
        if(n <= 0 || n > Integer.MAX_VALUE) return new int[0][0];
        
        int[][] directions = {{0, 1},{1, 0},{0, -1},{-1, 0}};
        int direction = 0, rNum = n, cNum = n,r = 0, c= -1, num = 1;
        int[][] rst = new int[n][n];
        int[] rcNum = {cNum, rNum};
        
        while(rcNum[direction % 2] > 0){
            for(int i = 0; i < rcNum[direction % 2]; i++){
                r += directions[direction % 4][0];
                c += directions[direction % 4][1];
                rst[r][c] = num++;
            }
            direction++;
            rcNum[direction % 2]--;
        }
        
        return rst;
        
        
    }
    

    }


Log in to reply
 

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