New: 214 pattern programs with tested code in C, C++, Java and Python Explore patterns

Spiral Walk From a Starting Cell

The spiral walk from a starting cell numbers a grid in the order you visit it when you spiral outwards from a chosen cell: 1 step east, 1 south, 2 west, 2 north, 3 east, and so on. It is LeetCode problem 885, “Spiral Matrix III”.

Quick answer: Walk in the directions east, south, west, north, using each step length twice before increasing it: 1, 1, 2, 2, 3, 3. Number every cell you land on that is inside the grid and skip the ones outside. Stop once every cell has a number.

This program is part of the Spiral Patterns collection.

Table of contents8 sections
  1. Output
  2. How the spiral walk from a starting cell works
  3. Program in C
  4. Program in C++
  5. Program in Java
  6. Program in Python
  7. Time and space complexity
  8. Frequently asked questions

Spiral Walk From a Starting Cell output

Output (4 × 5 grid, start at row 1, column 2):

 20  7  8  9 10
 19  6  1  2 11
 18  5  4  3 12
 17 16 15 14 13
Spiral Walk From a Starting Cell layout diagram, row by row (4 × 5 grid, start at row 1, column 2)
The numbers of the spiral walk from a starting cell laid out row by row (4 × 5 grid, start at row 1, column 2).

How the spiral walk from a starting cell works

An outward square spiral grows in a very regular way: after every two turns the straight runs get one step longer. That gives the step pattern 1, 1, 2, 2, 3, 3. The walk is allowed to leave the grid, which is what makes it simple; it just does not number the cells outside. Because the grid is a rectangle and the start is off-centre, the walk keeps going until the last cell inside has been reached.

  1. Number the starting cell 1 and face east with a step length of 1.
  2. Walk that many steps, numbering each cell that is inside the grid, then turn clockwise.
  3. Walk the same number of steps again and turn; then increase the step length by one.
  4. Repeat until every cell of the grid has a number, then print it.

Key takeaways

  • Step lengths go 1, 1, 2, 2, 3, 3: each is used twice.
  • The walk may leave the grid; only cells inside get a number.
  • The walk ends when the count reaches rows × columns.
  • The reverse spiral matrix is the same idea started from the centre of a square.

Spiral Walk From a Starting Cell in C

#include <stdio.h>

int main(void) {
    int rows = 4, cols = 5;
    int r = 1, c = 2;                           /* starting cell (row, column), counted from 0 */
    int a[4][5] = {{0}};
    int dr[] = {0, 1, 0, -1};                   /* east, south, west, north */
    int dc[] = {1, 0, -1, 0};
    int visited = 0, step = 1, d = 0;

    a[r][c] = ++visited;
    while (visited < rows * cols) {
        for (int twice = 0; twice < 2; twice++) {   /* each step length is used twice */
            for (int s = 0; s < step; s++) {
                r += dr[d];
                c += dc[d];
                if (r >= 0 && r < rows && c >= 0 && c < cols)
                    a[r][c] = ++visited;
            }
            d = (d + 1) % 4;
        }
        step++;
    }
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++)
            printf("%3d", a[i][j]);
        printf("\n");
    }
    return 0;
}

Spiral Walk From a Starting Cell in C++

#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

int main() {
    int rows = 4, cols = 5;
    int r = 1, c = 2;                           // starting cell (row, column), counted from 0
    vector<vector<int>> a(rows, vector<int>(cols, 0));
    int dr[] = {0, 1, 0, -1};                   // east, south, west, north
    int dc[] = {1, 0, -1, 0};
    int visited = 0, step = 1, d = 0;

    a[r][c] = ++visited;
    while (visited < rows * cols) {
        for (int twice = 0; twice < 2; twice++) {   // each step length is used twice
            for (int s = 0; s < step; s++) {
                r += dr[d];
                c += dc[d];
                if (r >= 0 && r < rows && c >= 0 && c < cols)
                    a[r][c] = ++visited;
            }
            d = (d + 1) % 4;
        }
        step++;
    }
    for (auto &row : a) {
        for (int x : row)
            cout << setw(3) << x;
        cout << endl;
    }
    return 0;
}

Spiral Walk From a Starting Cell in Java

public class SpiralWalkFromACell {
    public static void main(String[] args) {
        int rows = 4, cols = 5;
        int r = 1, c = 2;                           // starting cell (row, column), counted from 0
        int[][] a = new int[rows][cols];
        int[] dr = {0, 1, 0, -1};                   // east, south, west, north
        int[] dc = {1, 0, -1, 0};
        int visited = 0, step = 1, d = 0;

        a[r][c] = ++visited;
        while (visited < rows * cols) {
            for (int twice = 0; twice < 2; twice++) {   // each step length is used twice
                for (int s = 0; s < step; s++) {
                    r += dr[d];
                    c += dc[d];
                    if (r >= 0 && r < rows && c >= 0 && c < cols)
                        a[r][c] = ++visited;
                }
                d = (d + 1) % 4;
            }
            step++;
        }
        for (int[] row : a) {
            for (int x : row)
                System.out.printf("%3d", x);
            System.out.println();
        }
    }
}

Spiral Walk From a Starting Cell in Python

rows, cols = 4, 5
r, c = 1, 2                                 # starting cell (row, column), counted from 0
a = [[0] * cols for _ in range(rows)]
dr = [0, 1, 0, -1]                          # east, south, west, north
dc = [1, 0, -1, 0]
visited, step, d = 1, 1, 0

a[r][c] = visited
while visited < rows * cols:
    for twice in range(2):                  # each step length is used twice
        for s in range(step):
            r += dr[d]
            c += dc[d]
            if 0 <= r < rows and 0 <= c < cols:
                visited += 1
                a[r][c] = visited
        d = (d + 1) % 4
    step += 1
for row in a:
    print("".join(f"{x:3d}" for x in row))

Time and space complexity

The walk covers a square that grows to about twice the grid’s larger side, so it takes O(max(rows, cols)²) steps. The grid itself uses O(rows × cols) memory.

Frequently asked questions

Why are there zeros in my output for some starting cells?

There should not be: the walk continues until every cell is numbered. A zero means the loop stopped early, usually because the step length is increased after every turn instead of every second turn.

What does LeetCode 885 ask for?

It asks for the list of coordinates in visiting order. This program prints the visiting order inside the grid instead, which shows the same thing as a picture.

Can the walk start outside the grid?

The problem always starts inside. The code would still work from outside, numbering cells only once the walk reaches the grid.

This tutorial was drafted with AI assistance. Spotted a mistake? Tell us and we fix it. Read our editorial policy.

Quick check: can you predict the output?

Answer from the code, then check. Every answer comes from the real output above.

Pattern 13 of 14 in Spiral Patterns

 

Still stuck? Ask AI to explain this code

Opens your favourite AI with this page, ready to explain every loop step by step.

Authored by

Ghanendra Yadav runs Pattern Programs from Bangalore, India. The site started in 2020 to help students practise loops and logic through pattern programs in C, C++, Java and Python. Every program published here is compiled and run before it goes live, and the output shown is the real output.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.