59. Spiral Matrix II

public int[][] generateMatrix(int n) {
     
        int[][] res = new int[n][n];
        if (n <= 0) return res;
        
        int rowLo = 0;
        int rowHi = n-1;
        int colLo = 0;
        int colHi = n-1;
        int num = 1;
        
        while (rowLo <= rowHi && colLo <= colHi) {
     
            for (int i = colLo; i <= colHi; i++)
                res[rowLo][i] = num++;
            rowLo++;
            
            for (int i = rowLo; i <= rowHi; i++)
                res[i][colHi] = num++;
            colHi--;
            
            if (rowLo <= rowHi) {
     
                for (int i = colHi; i >= colLo; i--)
                    res[rowHi][i] = num++;
                rowHi--;
            }
            
            if (colLo <= colHi) {
     
                for (int i = rowHi; i >= rowLo; i--)
                    res[i][colLo] = num++;
                colLo++;
            }
            
        }
        return res;
    }

你可能感兴趣的:(leetcode)