# 74. 螺旋数字矩阵

74

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

rl.on('line', function(line) {
    const [m, n] = line.split(' ').map(Number);
    const cols = Math.ceil(n/m);
    const arr = Array.from({length:m}, () => Array(cols).fill(0));
    let num = 1;
    let top = 0;
    let bottom = m -1;
    let left=0;
    let right = cols - 1;
    while(num <= n) {
        for(let i=left; i<=right && num <= n; i++) {
            arr[top][i] = num++;
        }
        top++;
        for(let i=top; i<=bottom && num <= n; i++) {
            arr[i][right] = num++;
        }
        right--;
        for(let i=right; i>=left && num <= n; i--) {
            arr[bottom][i] = num++;
        }
        bottom--;
        for(let i=bottom; i>=top && num <= n; i--) {
            arr[i][left] = num++;
        }
        left++;
    }
    for(let i=0; i<m; i++) {
        let row = '';
        for(let j=0; j<cols; j++) {
            row += arr[i][j] === 0 ? '*' : arr[i][j];
            if (j < cols - 1) {
                row += ' ';
            }
        }
        console.log(row);
    }
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44