Rotate Image

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

Solution in Go

func rotate(matrix [][]int)  {
    startRow := 0
    startCol := 0
    endRow := len(matrix) - 1
    endCol := len(matrix[0]) - 1
    
    for startRow <= endRow && startCol <= endCol {
        for i := 0; i < endCol - startCol; i++ {
            temp := matrix[startRow][startCol + i]
            matrix[startRow][startCol + i] = matrix[endRow - i][startCol]
            matrix[endRow - i][startCol] = matrix[endRow][endCol - i]
            matrix[endRow][endCol - i] = matrix[startRow + i][endCol]
            matrix[startRow + i][endCol] = temp
        }
        
        startRow++
        startCol++
        endRow--
        endCol--
    }
}
Subscribe via email

Get notified once/twice per month when new articles are published.

Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.