Go: Spiral order

A slice of slices is the Go way to hold a table.

What to build

A program that prints the numbers of a table in spiral order, starting at the top left and going clockwise.

Requirements

  • Read r and c, then r rows of c numbers.
  • Print all numbers in spiral order on one line, separated by single spaces.

Input

Line 1: r and c. Then r lines with c numbers each.

Output

One line.

Constraints

1 ≤ r, c ≤ 10; numbers are between -100 and 100.

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

Each pass along one side uses up a row or a column, so the matching border moves inwards. The extra checks stop the walk from visiting a single remaining row or column 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, and move each border inwards.

Hint 2

Before walking the bottom row and the left column, check that rows or columns are left.

Solution

Show one correct solution (try it yourself first)
package main

import "fmt"

func main() {
	var r, c int
	fmt.Scan(&r, &c)
	m := make([][]int, r)
	for i := range m {
		m[i] = make([]int, c)
		for j := range m[i] {
			fmt.Scan(&m[i][j])
		}
	}
	out := []int{}
	top, bottom, left, right := 0, r-1, 0, c-1
	for top <= bottom && left <= right {
		for j := left; j <= right; j++ {
			out = append(out, m[top][j])
		}
		top++
		for i := top; i <= bottom; i++ {
			out = append(out, m[i][right])
		}
		right--
		if top <= bottom {
			for j := right; j >= left; j-- {
				out = append(out, m[bottom][j])
			}
			bottom--
		}
		if left <= right {
			for i := bottom; i >= top; i-- {
				out = append(out, m[i][left])
			}
			left++
		}
	}
	for i, v := range out {
		if i > 0 {
			fmt.Print(" ")
		}
		fmt.Print(v)
	}
	fmt.Println()
}

▶ Open this solution in the compiler

Lesson: Arrays and slices →