codelessgenie blog

Minimum Number of Integers Required to Fill an NxM Grid

Imagine you are tasked with designing a game board, scheduling tasks on a compute cluster, or creating a frequency allocation plan for cellular towers. A common constraint in these problems is that adjacent entities (squares, tasks, towers) cannot share the same property (color, resource, frequency). This fundamental constraint leads us to a classic problem: What is the minimum number of distinct integers (or labels) required to fill an N by M grid such that no two adjacent cells contain the same number?

This problem is not just a theoretical puzzle; it has practical applications in resource scheduling, map coloring, register allocation in compilers, and Sudoku puzzle design. In this technical blog, we will deconstruct this problem, explore efficient solutions, and discuss the underlying principles that make it work.

2026-06

Table of Contents#

  1. Introduction
  2. Problem Statement
  3. Understanding the Core Concept: Adjacency Constraint
  4. Approach 1: The Simple Two-Number Pattern (Chessboard Coloring)
  5. Approach 2: The General Case (Graph Coloring Perspective)
  6. Common Practices and Best Practices
  7. Example Usage Scenarios
  8. Conclusion
  9. References

Problem Statement#

Given a grid of size N rows and M columns, assign an integer to each cell. The assignment must satisfy the following condition:

  • Adjacent cells (sharing a common edge, i.e., up, down, left, right) must have different integers.

The goal is to find the minimum number of distinct integers, k, required to achieve such a valid assignment.

Examples:

  • A 1x1 grid: k = 1. (Only one cell, no adjacent cells to worry about).
  • A 2x2 grid: k = 2.
    Valid assignment:
    1 2
    2 1
    
  • A 3x3 grid: k = 2.
    Valid assignment (Chessboard pattern):
    1 2 1
    2 1 2
    1 2 1
    

Understanding the Core Concept: Adjacency Constraint#

The key to solving this problem lies in modeling the grid as a graph.

  • Each cell in the grid becomes a vertex in the graph.
  • An edge is drawn between two vertices if their corresponding cells are adjacent in the grid.

This graph is a well-known structure called a grid graph or lattice graph. Our problem now transforms into a classic graph theory problem: Find the chromatic number of the grid graph.

The chromatic number of a graph is the smallest number of colors needed to color the vertices so that no two adjacent vertices share the same color.

Approach 1: The Simple Two-Number Pattern (Chessboard Coloring)#

For the vast majority of cases where the grid has at least 2 cells, the answer is surprisingly simple.

Algorithm#

The most efficient and intuitive solution is to mimic the coloring of a chessboard.

  1. Check for Degenerate Case: If the grid has only one cell (N * M == 1), the minimum number of integers required is 1.
  2. Apply Chessboard Pattern: For all other cases (N * M > 1), the minimum number is 2.
  3. Assignment Strategy: Assign numbers based on the parity (evenness/oddness) of the cell's coordinates (i, j) where i is the row index and j is the column index (both starting from 0).
    • If (i + j) is even, assign the integer 1.
    • If (i + j) is odd, assign the integer 2.

Why does this work? Any two adjacent cells (up/down or left/right) will have a (i + j) sum that differs by exactly 1. Therefore, one sum will be even and the other will be odd, guaranteeing they receive different numbers.

Example Walkthrough#

Let's fill a 3x4 grid.

Step 1: Calculate (i + j) for each cell.

i=0, j=0: 0+0=0 (even) -> 1
i=0, j=1: 0+1=1 (odd)  -> 2
i=0, j=2: 0+2=2 (even) -> 1
i=0, j=3: 0+3=3 (odd)  -> 2

i=1, j=0: 1+0=1 (odd)  -> 2
i=1, j=1: 1+1=2 (even) -> 1
i=1, j=2: 1+2=3 (odd)  -> 2
i=1, j=3: 1+3=4 (even) -> 1

i=2, j=0: 2+0=2 (even) -> 1
i=2, j=1: 2+1=3 (odd)  -> 2
i=2, j=2: 2+2=4 (even) -> 1
i=2, j=3: 2+3=5 (odd)  -> 2

Step 2: The final grid is:

1 2 1 2
2 1 2 1
1 2 1 2

We have successfully used only 2 integers.

Code Implementation#

Here is a Python function that implements this logic.

def min_integers_to_fill_grid(n, m):
    """
    Calculates the minimum number of distinct integers needed to fill an n x m grid
    such that no two adjacent cells have the same number.
 
    Args:
        n (int): Number of rows.
        m (int): Number of columns.
 
    Returns:
        int: The minimum number of integers required (1 or 2).
    """
    if n == 1 and m == 1:
        return 1
    else:
        return 2
 
def fill_grid_with_pattern(n, m):
    """
    Generates a grid filled with the minimum number of integers (1 and 2)
    following the chessboard pattern.
 
    Args:
        n (int): Number of rows.
        m (int): Number of columns.
 
    Returns:
        list[list[int]]: A 2D list representing the filled grid.
    """
    grid = [[0] * m for _ in range(n)]
    for i in range(n):
        for j in range(m):
            # Assign 1 if (i+j) is even, else assign 2
            grid[i][j] = 1 if (i + j) % 2 == 0 else 2
    return grid
 
# Example Usage
if __name__ == "__main__":
    N, M = 3, 4
    k = min_integers_to_fill_grid(N, M)
    print(f"Minimum integers for a {N}x{M} grid: {k}")
 
    filled_grid = fill_grid_with_pattern(N, M)
    print("Filled grid:")
    for row in filled_grid:
        print(row)

Output:

Minimum integers for a 3x4 grid: 2
Filled grid:
[1, 2, 1, 2]
[2, 1, 2, 1]
[1, 2, 1, 2]

When is One Number Enough?#

The only scenario where one number suffices is when the grid graph has no edges. This happens only if there are no adjacent cells, which is true only for a 1x1 grid. For any larger grid (e.g., 1x2, 2x1, 2x2, etc.), there is at least one pair of adjacent cells, necessitating at least two numbers.

Approach 2: The General Case (Graph Coloring Perspective)#

While the two-number solution is optimal for standard grid adjacency, it's valuable to understand the general graph coloring framework, as the problem's constraints might change.

Graph Representation#

  1. Create a graph G with N*M vertices. You can label them as V_ij for cell (i, j).
  2. For each cell (i, j), add edges to its neighbors:
    • (i-1, j) if i > 0 (up)
    • (i+1, j) if i < N-1 (down)
    • (i, j-1) if j > 0 (left)
    • (i, j+1) if j < M-1 (right)

Chromatic Number#

The problem now is to find the chromatic number of graph G. For a general graph, this is an NP-hard problem. However, grid graphs are a special class:

  • They are bipartite graphs if they contain no cycles of odd length.
  • A grid graph is bipartite if and only if it is 2-colorable. This is true for all grid graphs with standard 4-direction adjacency.
  • Therefore, the chromatic number for a connected grid graph is 2. (The 1x1 grid is trivially 1-colorable as it has no edges).

Bipartite Check: You can perform a BFS or DFS to 2-color the graph. If you encounter a conflict (an edge connecting two vertices of the same color), the graph is not bipartite. For standard grids, this will never happen.

Why This is Often Overkill#

For the specific problem of a simple NxM grid with 4-direction adjacency, the graph coloring approach confirms what we already know from the chessboard pattern: the answer is always 1 or 2. Implementing a full BFS/DFS is computationally more expensive than the direct (i+j)%2 check and is unnecessary unless the adjacency rules change (e.g., including diagonal adjacency).

Common Practices and Best Practices#

  1. Start with the Simple Check: Always first check if the grid is 1x1. This is a best practice for handling edge cases efficiently.
  2. Use the Parity Formula: The (i + j) % 2 method is the most efficient way (O(1) time and O(N*M) for filling) to solve the standard problem. It is clean, easy to understand, and hard to get wrong.
  3. Clarify Adjacency Rules: In an interview or problem specification, always confirm the definition of "adjacent." Is it only 4-directional (von Neumann neighborhood) or does it include diagonals (Moore neighborhood)? This blog assumes 4-directional adjacency.
    • If diagonals are included, the problem becomes more complex, and the minimum number might be 4 (for grids larger than 2x2). This is akin to coloring a king's graph on a chessboard.
  4. Optimize for Space (if needed): If you only need to know the minimum number k and not the actual grid assignment, the function min_integers_to_fill_grid runs in O(1) time and O(1) space.

Example Usage Scenarios#

  • Task Scheduling on a Cluster: Imagine a cluster of machines arranged in a 2D mesh topology. Tasks that are adjacent (and might interfere) must be scheduled on different resource types. The minimum resource types needed is 2.
  • Game Board Design: When creating a tile-based game where adjacent tiles must be visually distinct, a designer can use a simple two-color pattern as a base.
  • Memory Allocation: In some low-level memory architectures, ensuring that adjacent memory blocks are handled by different banks can prevent conflicts. This problem helps determine the minimum number of banks required.

Conclusion#

The problem of finding the minimum number of integers to fill an NxM grid with adjacent cells being different has an elegant and simple solution. For all grids larger than 1x1, the answer is 2, achievable through a chessboard coloring pattern based on the parity of the cell coordinates (i + j). This solution is rooted in the graph-theoretic fact that grid graphs are bipartite and thus 2-colorable.

Understanding this fundamental principle allows developers to efficiently solve a class of resource allocation and constraint satisfaction problems. Always remember to clarify the problem's constraints, especially the definition of adjacency, as it is crucial to finding the correct solution.

References#

  1. Weisstein, Eric W. "Grid Graph." From MathWorld--A Wolfram Web Resource. https://mathworld.wolfram.com/GridGraph.html
  2. Weisstein, Eric W. "Chromatic Number." From MathWorld--A Wolfram Web Resource. https://mathworld.wolfram.com/ChromaticNumber.html
  3. "Graph Coloring." Wikipedia: The Free Encyclopedia. https://en.wikipedia.org/wiki/Graph_coloring
  4. "Bipartite Graph." Wikipedia: The Free Encyclopedia. https://en.wikipedia.org/wiki/Bipartite_graph