Golang Program to Print a Matrix in Spiral Format


To Print a matrix in spiral format we need to traverse the matrix in a spiral pattern, starting from the outermost layer and gradually moving inward. This approach provides a visually appealing way to display matrix elements. In this article we will use two methods to print a matrix in spiral format, the first method is by using the iterative approach and the other one is using the recursive approach. The examples below will help you understand these methods.

Explanation

Let us assume we have a 3 x 3 matrix, to print a matrix in spiral format we need to iterate through its elements in clockwise direction and print the first row and then the last column, after that last row in reverse and then the first column.

  • Print the first row: 1 2 3

  • Print last column: 6 9

  • Print last row in reverse: 8 7

  • Print first column in reverse : 4

  • Move inwards and print first row: 5

  • Print last column left to right: 7

Now, ignore the elements that are already printed so we will left with : 1 2 3 6 9 8 7 4 5

Algorithm

  • Create four variables: top, bottom, left, and right, representing the boundaries of the matrix.

  • Initialise the variables as follows:

    • top = 0

    • bottom = number of rows − 1

    • left = 0 (index of the leftmost column)

    • right = number of columns − 1

  • Create a loop that iterates while top <= bottom and left <= right:

    • Print the elements of the top row from left to right. Increment the top variable to move to the next row.

    • Print the elements of the rightmost column from top to bottom. Decrement the right variable to move to the previous column.

    • Check if top <= bottom. If true, proceed to the next steps. Otherwise, exit the loop. Print the elements of the bottom row from right to left.

    • Decrement the bottom variable to move to the previous row. Print the elements of the leftmost column from bottom to top. Increment the left variable to move to the next column.

  • After the loop ends, all the elements of the matrix will be printed in a spiral format.

Syntax

func printSpiralIterative(matrix [][]int)

The syntax defines a function named printSpiralIterative that takes a 2D integer matrix as input. This function uses an iterative approach to print the matrix elements in a spiral format. It iteratively traverses the matrix in a spiral pattern by tracking the boundary limits and adjusting the traversal direction.

func printSpiralRecursive(matrix [][]int)

The syntax declares a function named printSpiralRecursive that accepts a 2D integer matrix as an argument. This function uses a recursive approach to print the matrix elements in a spiral format. It recursively prints the elements of the matrix layer by layer, starting from the outermost layer and gradually moving inward.

Example

In this article we are going to use an iterative approach to print a matrix in spiral format. By defining the boundaries of the matrix and traversing it in a clockwise spiral pattern, we print the elements in the desired format. Let us Consider a 3 x 3 matrix with the following elements:

1 2 3

4 5 6

7 8 9

After applying the printSpiralIterative function to this matrix, the elements will be printed in a spiral format as follows: 1 2 3 6 9 8 7 4 5.

package main

import "fmt"

func printSpiralIterative(matrix [][]int) {
	if len(matrix) == 0 {
		return
	}

	top := 0
	bottom := len(matrix) - 1
	left := 0
	right := len(matrix[0]) - 1

	for top <= bottom && left <= right {
		for i := left; i <= right; i++ {
			fmt.Print(matrix[top][i], " ")
		}
		top++

		for i := top; i <= bottom; i++ {
			fmt.Print(matrix[i][right], " ")
		}
		right--

		if top <= bottom {
			for i := right; i >= left; i-- {
				fmt.Print(matrix[bottom][i], " ")
			}
			bottom--
		}

		if left <= right {
			for i := bottom; i >= top; i-- {
				fmt.Print(matrix[i][left], " ")
			}
			left++
		}
	}
}

func main() {
	matrix := [][]int{
		{1, 2, 3},
		{4, 5, 6},
		{7, 8, 9},
	}

	fmt.Println("Matrix in spiral format:")
	printSpiralIterative(matrix)
	fmt.Println()
}

Output

Matrix in spiral format:
1 2 3 6 9 8 7 4 5

Example

In this example we are going to use a recursive approach to Print a matrix in spiral format, by defining the boundaries of the matrix and recursively calling a helper function, we traverse the matrix in a clockwise spiral pattern and print the elements. Let us consider a 4 x 3 matrix with the following elements:

1 2 3

4 5 6

7 8 9

10 11 12

After applying the printSpiralRecursive function to this matrix, the elements will be printed in a spiral format as follows: 1 2 3 6 9 12 11 10 7 4 5 8.

package main

import "fmt"

func printSpiralRecursive(matrix [][]int) {
	printSpiralRecursiveHelper(matrix, 0, len(matrix)-1, 0, len(matrix[0])-1)
}

func printSpiralRecursiveHelper(matrix [][]int, top, bottom, left, right int) {
	if top > bottom || left > right {
		return
	}

	for i := left; i <= right; i++ {
		fmt.Print(matrix[top][i], " ")
	}
	top++

	for i := top; i <= bottom; i++ {
		fmt.Print(matrix[i][right], " ")
	}
	right--

	if top <= bottom {
		for i := right; i >= left; i-- {
			fmt.Print(matrix[bottom][i], " ")
		}
		bottom--
	}

	if left <= right {
		for i := bottom; i >= top; i-- {
			fmt.Print(matrix[i][left], " ")
		}
		left++
	}

	printSpiralRecursiveHelper(matrix, top, bottom, left, right)
}

func main() {
	matrix := [][]int{
		{1, 2, 3},
		{4, 5, 6},
		{7, 8, 9},
		{10, 11, 12},
	}

	fmt.Println("Matrix in spiral format:")
	printSpiralRecursive(matrix)
	fmt.Println()
}

Output

Matrix in spiral format:
1 2 3 6 9 12 11 10  7 4 5 8

Real life Implementation

Graphic Design Software

In graphic design software, such as image editors or CAD programs, displaying a matrix of pixel colors in a spiral format is useful. This allows users to visualize the color distribution across an image or design canvas. By printing pixels in a spiral pattern, designers can quickly identify patterns, anomalies, or areas requiring adjustments.

Game Development

In video game development, level design often involves grids or matrices representing terrain, obstacles, or gameplay elements. Printing these matrices in a spiral format can help developers visualize the level layout efficiently. It aids in analyzing the distribution of elements and identifying potential issues or imbalances in gameplay mechanics.

Conclusion

In this article we have looked at how we can print a matrix in spiral format in go language. This article shows two methods, the iterative and recursive approaches, to print a matrix in a spiral format. We have also looked at examples of each method to understand the concept. This can be used in graphic designing softwares and game development where we need to represent the gameplay.

Updated on: 07-Sep-2023

103 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements