既然没人用JS写,我就写了下,大家可以拿去copy copy看看


while(line=readline()){
    var n = line.split();

         let position = new Array();
        let str1 = "";
        for (i = 0; i < n; i++) {
            position[i] = new Array();
            for (j = 0; j < n; j++) {
                position[i][j] = -1;
            }
        }
        let state = 0;
        let x = 0;
        let y = 0;
        let trace = [];
        let cnt = 0;
        let allstate = [
            [1, -1],
            [-1, 1],
        ];
        let direction = [
            [1, 0],
            [0, 1],
        ];
        for (i = 0; i < n ** 2; i++) {
            cnt += 1;
            position[x][y] = cnt;
            x += allstate[state % 2][0];
            y += allstate[state % 2][1];
            if (
                (state % 2 === 0 || state === 0) &&
                (x >= n || x < 0 || y >= n || y < 0)
            ) {
                x -= allstate[state % 2][0];
                y -= allstate[state % 2][1];
                state += 1;
                x += direction[0][0];
                y += direction[0][1];
                if (x >= n || x < 0 || y >= n || y < 0) {
                    x -= direction[0][0];
                    y -= direction[0][1];
                    x += direction[1][0];
                    y += direction[1][1];
                }
            }
            if (
                (state % 2 !== 0 || state === 1) &&
                (x >= n || x < 0 || y >= n || y < 0)
            ) {
                x -= allstate[state % 2][0];
                y -= allstate[state % 2][1];
                state += 1;
                x += direction[1][0];
                y += direction[1][1];
                if (x >= n || x < 0 || y >= n || y < 0) {
                    x -= direction[1][0];
                    y -= direction[1][1];
                    x += direction[0][0];
                    y += direction[0][1];
                }
            }
        }
        // for (i = 0; i < n; i++) {
        //     for (j = 0; j < n; j++) {
        //         document.write(`<span>${position[i][j]}<span>  `);
        //     }
        //     document.write("<br>");
        // }
        for (i = 0; i < n; i++) {
            for (j = 0; j < n; j++) {
                str1 += `${position[j][i]} `;
            }
            str1 += "\n";
        }
        console.log(str1);
    
    
}