Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

Determine Whether Matrix Can Be Obtained By Rotation

Posted on July 19, 2022July 19, 2022 by admin

Overview

Two n*n matrices are given source and target. We have to determine whether the source matrix can be converted to the target matrix by doing 90-degree rotations any number of times

Example 1

Input: source = [2,1],[1,2]], target = [[1,2],[2,1]]
Output: true

The source matrix can be rotated 90 degrees once to obtain the target matrix

Example 2

Input:  source = [[1,2],[2,2]], target = [[2,1],[1,2]]
Output: false

Even if we rotate the source matrix 3 times by 90, obtaining the target matrix is impossible.

Program

Below is the program for the same

package main

import "fmt"

func findRotation(mat [][]int, target [][]int) bool {
	n, tmp := len(mat), make([]bool, 4)
	for i := range tmp {
		tmp[i] = true
	}
	for i := 0; i < n; i++ {
		for j := 0; j < n; j++ {
			if mat[i][j] != target[i][j] {
				tmp[0] = false
			}
			if mat[i][j] != target[j][n-i-1] {
				tmp[1] = false
			}
			if mat[i][j] != target[n-i-1][n-j-1] {
				tmp[2] = false
			}
			if mat[i][j] != target[n-j-1][i] {
				tmp[3] = false
			}
		}
	}
	return tmp[0] || tmp[1] || tmp[2] || tmp[3]
}

func main() {
	output := findRotation([][]int{{2, 1}, {1, 2}}, [][]int{{1, 2}, {2, 1}})
	fmt.Println(output)

	output = findRotation([][]int{{1, 2}, {2, 2}}, [][]int{{2, 1}, {1, 2}})
	fmt.Println(output)

}

Output

true
false

Also, check out our system design tutorial series here – System Design Tutorial Series

©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme