SIMPLEST JAVA solution


  • 0
    V
        public int[][] generateMatrix(int n) {
            int[][] ret = new int[n][n];
            int c = -1, r = 0;
            int numRows = n, numCols = n;
            int count = 1;
            
            while (numRows > 0 && numCols > 0) {
                for(int i=0; i<numCols; i++) ret[r][++c] = count++;;
                if (--numRows == 0) break;
                
                for(int i=0; i<numRows; i++) ret[++r][c] = count++;
                if(--numCols == 0) break;
                
                for(int i=0; i<numCols; i++) ret[r][--c] = count++;
                if(--numRows == 0) break;
                
                for(int i=0; i<numRows; i++) ret[--r][c] = count++;
                if(--numCols == 0) break;
            }
            
            return ret;
        }
    

Log in to reply
 

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