← 返回 waymo 的题目列表Randomly Generate a Fully-Populated Grid with 4 Equal-Size Connected Components
类型:online_judge
Problem
Given an m × n grid, fill it completely with 4 tokens labeled 1, 2, 3, 4 such that:
Every cell is assigned exactly one token (no empty cells).
Each token must occupy the same number of cells. Therefore m*n must be divisible by 4 (otherwise there is no solution).
For each token, all its cells must form one connected component.
Connectivity is 4-directional only (up, down, left, right).
Task:
Design and implement an algorithm that randomly generates a grid satisfying all constraints.
If a single attempt fails to produce a valid grid, you may retry, but describe the retry strategy.
Input
Two integers m, n.
Output
Print an m × n integer grid (each row has n integers), each in {1,2,3,4}, satisfying the constraints.
Constraints (if not explicitly provided, you may assume)
Suggested: 1 ≤ m, n ≤ 30.
Example (illustrative only)
Input:
4 4
Possible output:
1 1 2 2
1 3 3 2
4 3 2 2
4 4 4 4
(The example is only for output format; actual output must have equal counts and each token connected.)
Example
Input
4 4
Output
(any valid 4x4 grid with each token appearing 4 times and each token 4-connected)