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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,788 questions

51,694 answers

573 users

How to generate an n x n matrix filled with elements from 1 to N^2 in spiral order in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

func generateSpiralMatrix(n int) [][]int {
    // Initialize an n x n matrix with zeros
    matrix := make([][]int, n)
    for i := range matrix {
        matrix[i] = make([]int, n)
    }

    top, bottom := 0, n-1
    left, right := 0, n-1
    num := 1

    for top <= bottom && left <= right {
        // Fill top row
        for i := left; i <= right; i++ {
            matrix[top][i] = num
            num++
        }
        top++

        // Fill right column
        for i := top; i <= bottom; i++ {
            matrix[i][right] = num
            num++
        }
        right--

        // Fill bottom row
        if top <= bottom {
            for i := right; i >= left; i-- {
                matrix[bottom][i] = num
                num++
            }
            bottom--
        }

        // Fill left column
        if left <= right {
            for i := bottom; i >= top; i-- {
                matrix[i][left] = num
                num++
            }
            left++
        }
    }

    return matrix
}

func main() {
    n := 3
    matrix := generateSpiralMatrix(n)

    // Print the matrix
    for _, row := range matrix {
        for _, val := range row {
            fmt.Printf("%d\t", val)
        }
        fmt.Println()
    }
}



/*
run:

1	2	3	
8	9	4	
7	6	5	

*/

 



answered Jun 25, 2025 by avibootz
...