Java: Read a grid in a spiral

Two-dimensional arrays need careful index work. Visit a grid's cells in a clockwise spiral from the top left.

What to build

A program that prints a grid's values in spiral order.

Requirements

  • Read r and c, then r rows of c numbers into an int[][].
  • Print the values in clockwise spiral order from the top-left corner, separated by spaces.

Input

Line 1: r and c. Then r lines of c numbers.

Output

One line.

Constraints

1 ≤ r, c ≤ 50.

Example

Input:

3 3
1 2 3
4 5 6
7 8 9

Output:

1 2 3 6 9 8 7 4 5

Why it works

Four shrinking borders mark the part of the grid not yet visited; each side of the spiral is one loop, and the checks between them stop a single remaining row or column from being visited twice.

Examples

Example 1 · Input
3 3
1 2 3
4 5 6
7 8 9
Expected output
1 2 3 6 9 8 7 4 5
Example 2 · Input
2 4
1 2 3 4
5 6 7 8
Expected output
1 2 3 4 8 7 6 5

Hints

Hint 1

Keep four borders: top, bottom, left, right. Walk the top row, the right column, the bottom row and the left column, then move the borders in.

Hint 2

Stop when top passes bottom or left passes right; check again before the bottom row and the left column.

Solution

Show one correct solution (try it yourself first)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int r = in.nextInt(), c = in.nextInt();
        int[][] g = new int[r][c];
        for (int i = 0; i < r; i++) for (int j = 0; j < c; j++) g[i][j] = in.nextInt();
        StringBuilder sb = new StringBuilder();
        int top = 0, bottom = r - 1, left = 0, right = c - 1;
        while (top <= bottom && left <= right) {
            for (int j = left; j <= right; j++) sb.append(g[top][j]).append(' ');
            top++;
            for (int i = top; i <= bottom; i++) sb.append(g[i][right]).append(' ');
            right--;
            if (top <= bottom) {
                for (int j = right; j >= left; j--) sb.append(g[bottom][j]).append(' ');
                bottom--;
            }
            if (left <= right) {
                for (int i = bottom; i >= top; i--) sb.append(g[i][left]).append(' ');
                left++;
            }
        }
        System.out.println(sb.toString().trim());
    }
}

Lesson: Arrays →