{ }codelper
filled listsswapping values2D listsP0128

Spiral fill

Fill a board of r rows and c columns with the numbers 1 to r × c in a spiral. The first line gives r and c. Write 1 in the top-left cell and keep writing the next number while moving right. If the next cell is outside the board or already has a number, turn 90 degrees clockwise (right → down → left → up → right) and write in the cell that way. When the board is full, print it row by row. Right-align each number to a width equal to the number of digits of r × c (pad the front with spaces), with one space between numbers.

Input
1 ≤ r ≤ 50, 1 ≤ c ≤ 50
Output
r lines, c numbers per line
Example 1 · stdin
3 4
stdout
 1  2  3  4
10 11 12  5
 9  8  7  6
Example 2 · stdin
4 3
stdout
 1  2  3
10 11  4
 9 12  5
 8  7  6
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

The first trap is how you build a board filled with 0.
Python [[0] * c] * r puts one row list in r times, so writing one cell changes that cell in every row.
Build each row anew with [[0] * c for _ in range(r)].
JS/TS new Array(r).fill(new Array(c).fill(0)) also puts the same array in every slot, so write Array.from({ length: r }, () => new Array(c).fill(0)).
Java new int[r][c], C# new int[r, c] and a global C array start at 0, and C++ vector(r, vector<int>(c, 0)) copies each row.
Craykon NewList(r, NewList(c, 0)) also copies the value into each slot.
Turning clockwise means changing (dy, dx) into (dx, -dy), which is a swap of two values.
Python dy, dx = dx, -dy, JS/TS [dy, dx] = [dx, -dy], C# (dy, dx) = (dx, -dy) change both at once, and C++ can write std::swap(dy, dx); dx = -dx; without a temporary, but Java, C and Craykon need a temporary t = dy; dy = dx; dx = -t;.
Writing dy = dx; dx = -dy; without the temporary uses the already changed dy on the second line and walks diagonally.
The width is the number of digits of r × c (3 for 100 cells, for example).
Align with Python str(v).rjust(w), JS/TS padStart(w), Java String.format("%" + w + "d", v), C printf("%*d", w, v), C++ std::setw(w), C# PadLeft(w), Craykon PadLeft(w).

Pythonmain.py · 14 lines
r, c = map(int, input().split())grid = [[0] * c for _ in range(r)]  # 줄마다 새 목록(같은 목록을 r번 넣지 않게)y, x = 0, 0dy, dx = 0, 1  # 오른쪽으로 시작for k in range(1, r * c + 1):    grid[y][x] = k    ny, nx = y + dy, x + dx    if not (0 <= ny < r and 0 <= nx < c and grid[ny][nx] == 0):        dy, dx = dx, -dy  # 시계 방향으로 90도: 두 값을 맞바꾸며 부호 하나를 뒤집는다        ny, nx = y + dy, x + dx    y, x = ny, nxwidth = len(str(r * c))for row in grid:    print(" ".join(str(v).rjust(width) for v in row))
JavaScriptmain.js · 18 lines
const [r, c] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);// 줄마다 새 배열(fill에 배열 하나를 주면 모든 줄이 같은 배열이 된다)const grid = Array.from({ length: r }, () => new Array(c).fill(0));let y = 0, x = 0;let dy = 0, dx = 1; // 오른쪽으로 시작for (let k = 1; k <= r * c; k++) {  grid[y][x] = k;  let ny = y + dy, nx = x + dx;  if (!(ny >= 0 && ny < r && nx >= 0 && nx < c && grid[ny][nx] === 0)) {    [dy, dx] = [dx, -dy]; // 시계 방향으로 90도    ny = y + dy;    nx = x + dx;  }  y = ny;  x = nx;}const width = String(r * c).length;console.log(grid.map((row) => row.map((v) => String(v).padStart(width)).join(" ")).join("\n"));
TypeScriptmain.ts · 19 lines
import { readFileSync } from "node:fs";const [r, c]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);// 줄마다 새 배열(fill에 배열 하나를 주면 모든 줄이 같은 배열이 된다)const grid: number[][] = Array.from({ length: r }, () => new Array<number>(c).fill(0));let y = 0, x = 0;let dy = 0, dx = 1; // 오른쪽으로 시작for (let k = 1; k <= r * c; k++) {  grid[y][x] = k;  let ny = y + dy, nx = x + dx;  if (!(ny >= 0 && ny < r && nx >= 0 && nx < c && grid[ny][nx] === 0)) {    [dy, dx] = [dx, -dy]; // 시계 방향으로 90도    ny = y + dy;    nx = x + dx;  }  y = ny;  x = nx;}const width: number = String(r * c).length;console.log(grid.map((row) => row.map((v) => String(v).padStart(width)).join(" ")).join("\n"));
JavaMain.java · 35 lines
import java.util.Scanner; public class Main {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int r = sc.nextInt();        int c = sc.nextInt();        int[][] grid = new int[r][c]; // 칸마다 0으로 채워져 있다        int y = 0, x = 0;        int dy = 0, dx = 1; // 오른쪽으로 시작        for (int k = 1; k <= r * c; k++) {            grid[y][x] = k;            int ny = y + dy, nx = x + dx;            if (!(ny >= 0 && ny < r && nx >= 0 && nx < c && grid[ny][nx] == 0)) {                int t = dy; // 시계 방향으로 90도: 임시 변수로 맞바꾼다                dy = dx;                dx = -t;                ny = y + dy;                nx = x + dx;            }            y = ny;            x = nx;        }        String fmt = "%" + String.valueOf(r * c).length() + "d";        StringBuilder out = new StringBuilder();        for (int[] row : grid) {            for (int j = 0; j < c; j++) {                if (j > 0) out.append(' ');                out.append(String.format(fmt, row[j]));            }            out.append('\n');        }        System.out.print(out);    }}
C#Main.cs · 40 lines
using System;using System.Linq;using System.Text; class Program{    static void Main()    {        int[] rc = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();        int r = rc[0], c = rc[1];        int[,] grid = new int[r, c]; // 칸마다 0으로 채워져 있다        int y = 0, x = 0;        int dy = 0, dx = 1; // 오른쪽으로 시작        for (int k = 1; k <= r * c; k++)        {            grid[y, x] = k;            int ny = y + dy, nx = x + dx;            if (!(ny >= 0 && ny < r && nx >= 0 && nx < c && grid[ny, nx] == 0))            {                (dy, dx) = (dx, -dy); // 시계 방향으로 90도: 튜플로 맞바꾼다                ny = y + dy;                nx = x + dx;            }            y = ny;            x = nx;        }        int width = (r * c).ToString().Length;        var sb = new StringBuilder();        for (int i = 0; i < r; i++)        {            for (int j = 0; j < c; j++)            {                if (j > 0) sb.Append(' ');                sb.Append(grid[i, j].ToString().PadLeft(width));            }            sb.Append('\n');        }        Console.Write(sb);    }}
C++main.cpp · 33 lines
#include <iomanip>#include <iostream>#include <string>#include <utility>#include <vector> int main() {    int r, c;    std::cin >> r >> c;    std::vector<std::vector<int>> grid(r, std::vector<int>(c, 0)); // 줄마다 따로 복사된다    int y = 0, x = 0;    int dy = 0, dx = 1; // 오른쪽으로 시작    for (int k = 1; k <= r * c; k++) {        grid[y][x] = k;        int ny = y + dy, nx = x + dx;        if (!(ny >= 0 && ny < r && nx >= 0 && nx < c && grid[ny][nx] == 0)) {            std::swap(dy, dx); // 시계 방향으로 90도: 맞바꾸고            dx = -dx;          // 부호 하나를 뒤집는다            ny = y + dy;            nx = x + dx;        }        y = ny;        x = nx;    }    int width = std::to_string(r * c).size();    for (const auto& row : grid) {        for (int j = 0; j < c; j++) {            if (j > 0) std::cout << ' ';            std::cout << std::setw(width) << row[j];        }        std::cout << '\n';    }}
Cmain.c · 29 lines
#include <stdio.h> int grid[50][50]; // 전역 배열은 0으로 채워져 있다 int main(void) {    int r, c;    scanf("%d %d", &r, &c);    int y = 0, x = 0;    int dy = 0, dx = 1; // 오른쪽으로 시작    for (int k = 1; k <= r * c; k++) {        grid[y][x] = k;        int ny = y + dy, nx = x + dx;        if (!(ny >= 0 && ny < r && nx >= 0 && nx < c && grid[ny][nx] == 0)) {            int t = dy; // 시계 방향으로 90도: 임시 변수로 맞바꾼다            dy = dx;            dx = -t;            ny = y + dy;            nx = x + dx;        }        y = ny;        x = nx;    }    int width = snprintf(NULL, 0, "%d", r * c); // r*c의 자릿수    for (int i = 0; i < r; i++) {        for (int j = 0; j < c; j++) printf(j ? " %*d" : "%*d", width, grid[i][j]);        putchar('\n');    }    return 0;}
Craykonmain.cray · 35 lines
rc = Console.ReadNumbers();r = rc[0];c = rc[1];// 새목록에 목록을 주면 줄마다 따로 복사해 넣는다grid = NewList(r, NewList(c, 0));y = 0;x = 0;dy = 0;dx = 1; // 오른쪽으로 시작for (k = 1; k <= r * c; k++){    grid[y][x] = k;    ny = y + dy;    nx = x + dx;    if (!(ny >= 0 && ny < r && nx >= 0 && nx < c && grid[ny][nx] == 0))    {        t = dy; // 시계 방향으로 90도: 임시 변수로 맞바꾼다        dy = dx;        dx = -t;        ny = y + dy;        nx = x + dx;    }    y = ny;    x = nx;}width = ("" + r * c).Length;foreach (row in grid){    cells = [];    foreach (v in row)    {        cells.Add(("" + v).PadLeft(width));    }    Console.WriteLine(cells.Join(" "));}