Skip to main content

Anticlockwise spiral view of diamond matrix elements in golang

Anticlockwise spiral view of matrix

Go program for Anticlockwise spiral view of diamond matrix elements. Here mentioned other language solution.

package main
import "fmt"
/*
  Go program for
  Anticlockwise spiral view of diamond element in matrix
*/

// Method which is displaying the Anticlockwise spiral 
// Of matrix in diamond(mid) element
func spiralView(matrix[][] int, x int, 
    y int, p int, q int, k int) {
    // Find the middle column
    var midCol int = y + ((q - y) / 2)
    // Get middle row (valid for odd square matrix)
    var midRow int = midCol
    // Matrix are divided into 4 section
    // Starting of middle row and column in form of top
    // Case A
    // Top to Left-bottom
    var i int = midCol
    var j int = 0
    for (i > y && k > 0) {
        fmt.Print("  ", matrix[x + j][i])
        i--
        k--
        j++
    }
    // Case B
    // Middle left to middle right bottom
    i = y
    j = 0
    for (i <= midCol && k > 0) {
        fmt.Print("  ", matrix[(midRow) + j][i])
        i++
        k--
        j++
    }
    // Case C
    // Middle bottom to middle right side 
    i = midCol + 1
    j = 1
    for (i <= q && k > 0) {
        fmt.Print("  ", matrix[(p) - j][i])
        i++
        k--
        j++
    }
    // Case D
    // Middle right side to  top middle 
    i = q - 1
    j = 1
    for (i > midCol && k > 0) {
        fmt.Print("  ", matrix[(midRow) - j][i])
        i--
        k--
        j++
    }
    if x + 1 <= p - 1 && k > 0 {
        // Recursive call
        spiralView(matrix, x + 1, y + 1, p - 1, q - 1, k)
    }
}
func diamondAnticlockwise(matrix[][] int) {
    var row int = len(matrix)
    var col int = len(matrix[0])
    // Check whether the given matrix is a valid odd shape or not
    if row != col || col % 2 == 0 {
        // When Yes not a valid size
        fmt.Println("\nNot a valid perfect Odd square matrix")
        return
    }
    // (row*col)-((col+1)/2)*4 are provide the value of number of 
    // Diamond element
    spiralView(matrix, 0, 0, row - 1, col - 1, 
        (row * col) - ((col + 1) / 2) * 4)
}
func main() {
    // Define matrix 
    var matrix = [][] int {
        {1,  2,  3,  4,  5},
        {6,  7,  8,  9,  10},
        {11, 12, -1, 15,  16},
        {17, 18, 19, 20,  21},
        {22, 23, 24, 25,  26}}
    diamondAnticlockwise(matrix)
}

Output

   3   7  11  18  24  20  16   9   8  12  19  15  -1




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment