How to rotate a matrix 90 degrees clockwise in Go

2 Answers

0 votes
package main

import (
    "fmt"
)

// rotate90Clockwise rotates a square matrix 90 degrees clockwise.
func rotate90Clockwise(matrix [][]int) {
    N := len(matrix)

    // Step 1: Transpose the matrix
    for i := 0; i < N; i++ {
        for j := i; j < N; j++ {
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
        }
    }

    // Step 2: Reverse each row
    for i := 0; i < N; i++ {
        reverse(matrix[i])
    }
}

// reverse reverses an array in place.
func reverse(row []int) {
    left, right := 0, len(row)-1
    for left < right {
        row[left], row[right] = row[right], row[left]
        left++
        right--
    }
}

// printMatrix prints the matrix in a readable format.
func printMatrix(matrix [][]int) {
    for _, row := range matrix {
        for _, val := range row {
            fmt.Print(val, " ")
        }
        fmt.Println()
    }
}

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

    fmt.Println("Original Matrix:")
    printMatrix(matrix)

    rotate90Clockwise(matrix)

    fmt.Println("\nRotated Matrix:")
    printMatrix(matrix)
}


 
 
/*
run:
 
Original Matrix:
1 2 3 
4 5 6 
7 8 9 

Rotated Matrix:
7 4 1 
8 5 2 
9 6 3 
 
*/

 



answered May 30 by avibootz
0 votes
package main

import (
    "fmt"
)

// rotate90Clockwise rotates a matrix 90 degrees clockwise.
func rotate90Clockwise(matrix [][]int) [][]int {
    rows := len(matrix)
    cols := len(matrix[0])

    // Create a new rotated matrix
    rotated := make([][]int, cols)
    for i := range rotated {
        rotated[i] = make([]int, rows)
    }

    // Map values to rotated positions
    for i := 0; i < rows; i++ {
        for j := 0; j < cols; j++ {
            rotated[j][rows-1-i] = matrix[i][j]
        }
    }

    return rotated
}

// printMatrix prints the matrix in a readable format.
func printMatrix(matrix [][]int) {
    for _, row := range matrix {
        fmt.Println(row)
    }
}

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

    fmt.Println("Original Matrix:")
    printMatrix(matrix)

    rotated := rotate90Clockwise(matrix)

    fmt.Println("\nRotated Matrix:")
    printMatrix(rotated)
}

 
 
/*
run:
 
Original Matrix:
[1 2 3 4]
[5 6 7 8]
[9 10 11 12]

Rotated Matrix:
[9 5 1]
[10 6 2]
[11 7 3]
[12 8 4]
 
*/

 



answered May 30 by avibootz
...