Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Semrush - keyword research tool

Linux Foundation Training and Certification

Teach Your Child To Read

Disclosure: My content contains affiliate links.

32,310 questions

42,485 answers

573 users

How to print a given matrix in spiral form with Go

1 Answer

0 votes
package main

import "fmt"

func PrintMatrixInSpiralForm(matrix [][]int) {
	if matrix == nil || len(matrix) == 0 {
		return
	}

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

	for {
		if left > right {
			break
		}

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

		if top > bottom {
			break
		}

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

		if left > right {
			break
		}

		// bottom row
		for i := right; i >= left; i-- {
			fmt.Print(matrix[bottom][i], " ")
		}
		fmt.Println()
		bottom-- // previous row

		if top > bottom {
			break
		}

		// left column
		for i := bottom; i >= top; i-- {
			fmt.Print(matrix[i][left], " ")
		}
		fmt.Println()
		left++ // next column
	}
}

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

	PrintMatrixInSpiralForm(matrix)
}


/*
run:

1 2 3 4 
8 12 16 
15 14 13 
9 5 
6 7 
11 
10 

*/

 



Learn & Practice Python
with the most comprehensive set of 13 hands-on online Python courses
Start now


answered Sep 3 by avibootz

Related questions

1 answer 9 views
1 answer 11 views
1 answer 56 views
1 answer 53 views
1 answer 65 views
...