Amazon Interview Question
SDE1sCountry: United States
n is the square matrix dimension.
Think of the matrix as a series of hollow rectangles that wrap each other. The layer (l) is the current rectangle of elements. In the example there are two layers - a layer of size 3 and a layer of size 1 (but we ignore the layer of size 1 since it does not require rotation).
I should clarify - I call the "size" of the layer to be the size of the rectangle side, not the total number of elements in the layer.
why do you say "assuming a square matrix" ? You don't have to assume it, it's specifically mentioned in the question.
Also the solution is wrong. You rotate all square frames by 1, but that is not correct. The 3x3 square frame is rotate by 1, but the next square frame 5x5 (in a 5x5 matrix or larger) should be rotated by 2 to keep the values aligned with next smaller square frame).
For example:
[11, 12, 13, 14, 15]
[21, 22, 23, 24, 25]
[31, 32, 33, 34, 35]
[41, 42, 43, 44, 45]
[51, 52, 53, 54, 55]
rotated:
[31, 21, 11, 12, 13]
[41, 32, 22, 23, 14]
[51, 42, 33, 24, 15]
[52, 43, 44, 34, 25]
[53, 54, 55, 45, 35]
def rotate_matrix(m):
# rotate shell around matrix
tmp = m[0][0]
# first move who thing up for first column
col_i = 0
for i in range(len(m)-1):
m[i][col_i] = m[i+1][col_i]
# next move columns left for bottom row
row_i = len(m)-1
for j in range(len(m)-1):
m[row_i][j] = m[row_i][j+1]
# next move rows down for last column
col_i = len(m)-1
for i in range(len(m)-1, 0, -1):
m[i][col_i] = m[i-1][col_i]
# next move columns right for top for
row_i = 0
for i in range(len(m)-1, 0, -1):
m[row_i][i] = m[row_i][i-1]
# lastly, fill in tmp
m[0][1] = tmp
def rotate_matrix(m):
# rotate shell around matrix
tmp = m[0][0]
# first move who thing up for first column
col_i = 0
for i in range(len(m)-1):
m[i][col_i] = m[i+1][col_i]
# next move columns left for bottom row
row_i = len(m)-1
for j in range(len(m)-1):
m[row_i][j] = m[row_i][j+1]
# next move rows down for last column
col_i = len(m)-1
for i in range(len(m)-1, 0, -1):
m[i][col_i] = m[i-1][col_i]
# next move columns right for top for
row_i = 0
for i in range(len(m)-1, 0, -1):
m[row_i][i] = m[row_i][i-1]
# lastly, fill in tmp
m[0][1] = tmp
private void rotate(){
// Copy a item to the next using a temp variable that keeps the target value
int i=0, j=0;
int temp, dataToStore = data[i][j];
while(true){
int[] nextIdxs = rotateClockwise(i, j);
i = nextIdxs[0];
j = nextIdxs[1];
temp = data[i][j]; // For storing the data in next iteration.
data[i][j] = dataToStore;
dataToStore = temp;
if(i == 0 && j == 0){
break;
}
}
}
private int[] rotateClockwise(int i, int j){
if(i== 0 && j<(data[i].length-1)){
// Increment j
++j;
} else if(i < (data.length -1) && j == (data[i].length-1)){
// Increment i
++i;
} else if(i == (data.length-1) && j > 0){
// Decrement j
--j;
} else if(i > 0 && j == 0){
// Decrement i
--i;
}
System.out.println(i + " " + j);
return new int[]{i,j};
}
public static void rotateMatrix(int [][] matrix, int m,int n){
int [][] dir = {{0,1},{1,0},{0,-1},{-1,0}};
int current = matrix[0][0];
int x = 0;
int y = 0;
int cDir = 0;
for(int i = 0 ; i < (m*n) -1; i++){
if((x+dir[cDir][0]>=m) || (x+dir[cDir][0]<0) || (y+dir[cDir][1]>=n) || (y+dir[cDir][1]<0)){
cDir++;
}
x = x+dir[cDir][0];
y = y+dir[cDir][1];
int temp = matrix[x][y];
matrix[x][y] = current;
current = temp;
}
// print output
for(int i = 0 ; i < m; i++){
for(int j = 0 ; j < n; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println("");
}
}
public static void Main(string[] args)
{
int[,] values = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }};
DisplayValues(values);
RotateValues(values);
DisplayValues(values);
Console.ReadKey();
}
private static void DisplayValues(int[,] values)
{
for (int i = 0; i < values.GetLength(0); i++)
{
var sb = new System.Text.StringBuilder();
var sep = "";
for (int y = 0; y < values.GetLength(1); y++)
{
sb.Append(sep);
sb.Append(values[i, y]);
sep = "->";
}
Console.WriteLine(sb.ToString());
}
Console.WriteLine();
}
private static void RotateValues(int[,] values)
{
int maxRowIndex = values.GetLength(0) - 1;
int maxColumnIndex = values.GetLength(1) - 1;
int previousValue = values[0, 0];
int cache;
for (int row = 0; row <= maxRowIndex; row++)
{
if (row == 0) {
for (int column = 0; column <= maxColumnIndex; column++)
{
if (column != maxColumnIndex)
{
cache = values[row, column + 1];
values[row, column + 1] = previousValue;
previousValue = cache;
}
}
} else if (row == maxRowIndex ) {
for (int column = maxColumnIndex; column >= 0; column--)
{
if (column == 0)
{
values[row - 1, 0] = values[row, column];
}
cache = values[row, column];
values[row, column] = previousValue;
previousValue = cache;
}
} else {
for (int column = maxColumnIndex; column >= 0; column--)
{
if (column == maxColumnIndex)
{
cache = values[row, column];
values[row, column] = previousValue;
previousValue = cache;
}
else if (column == 0)
{
values[row - 1, 0] = values[row, column];
}
}
}
}
}
#include <iostream>
#include <vector>
template <typename T, size_t W, size_t H>
std::ostream& operator<<(std::ostream &os, T(&obj)[W][H]) {
for(size_t i = 0; i < H; ++i)
{
for(size_t j = 0; j < W; ++j)
{
os<<obj[i][j]<<" ";
}
os<<std::endl;
}
return os;
}
template <typename T, size_t W, size_t H>
void rotate(T(&a)[W][H]){
T tmp = a[0][0];
for(size_t i = 1; i < H; ++i) std::swap(a[i-1][0], a[i][0]);
for(size_t i = 1; i < W; ++i) std::swap(a[H-1][i-1], a[H-1][i]);
for(size_t i = 1; i < H; ++i) std::swap(a[H-i][W-1], a[H-i-1][W-1]);
for(size_t i = 1; i < W-1; ++i) std::swap(a[0][W-i], a[0][W-i-1]);
}
int main(){
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
std::cout<<"Orig. Matrix:\n"<<a;
rotate(a);
std::cout<<"Result Matrix:\n"<<a;
char b[4][4] = {{'a','b','c','d'},{'e','f','g','h'},{'i','j','k','l'},{'m','n','o','p'}};
std::cout<<b<<"\n";
rotate(b);
std::cout<<b<<"\n";
return 0;
}
output:
Orig. Matrix:
1 2 3
4 5 6
7 8 9
Result Matrix:
4 1 2
7 5 3
8 9 6
a b c d
e f g h
i j k l
m n o p
e a b c
i f g d
m j k h
n o p l
#include <iostream>
#include <vector>
template <typename T, size_t W, size_t H>
std::ostream& operator<<(std::ostream &os, T(&obj)[W][H]) {
for(size_t i = 0; i < H; ++i)
{
for(size_t j = 0; j < W; ++j)
{
os<<obj[i][j]<<" ";
}
os<<std::endl;
}
return os;
}
template <typename T, size_t W, size_t H>
void rotate(T(&a)[W][H]){
T tmp = a[0][0];
for(size_t i = 1; i < H; ++i) std::swap(a[i-1][0], a[i][0]);
for(size_t i = 1; i < W; ++i) std::swap(a[H-1][i-1], a[H-1][i]);
for(size_t i = 1; i < H; ++i) std::swap(a[H-i][W-1], a[H-i-1][W-1]);
for(size_t i = 1; i < W-1; ++i) std::swap(a[0][W-i], a[0][W-i-1]);
}
int main(){
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
std::cout<<"Orig. Matrix:\n"<<a;
rotate(a);
std::cout<<"Result Matrix:\n"<<a;
char b[4][4] = {{'a','b','c','d'},{'e','f','g','h'},{'i','j','k','l'},{'m','n','o','p'}};
std::cout<<b<<"\n";
rotate(b);
std::cout<<b<<"\n";
return 0;
}
OUTPUT:
Orig. Matrix:
1 2 3
4 5 6
7 8 9
Result Matrix:
4 1 2
7 5 3
8 9 6
a b c d
e f g h
i j k l
m n o p
e a b c
i f g d
m j k h
n o p l
#include <iostream>
#include <vector>
template <typename T, size_t W, size_t H>
std::ostream& operator<<(std::ostream &os, T(&obj)[W][H]) {
for(size_t i = 0; i < H; ++i)
{
for(size_t j = 0; j < W; ++j)
{
os<<obj[i][j]<<" ";
}
os<<std::endl;
}
return os;
}
template <typename T, size_t W, size_t H>
void rotate(T(&a)[W][H]){
T tmp = a[0][0];
for(size_t i = 1; i < H; ++i) std::swap(a[i-1][0], a[i][0]);
for(size_t i = 1; i < W; ++i) std::swap(a[H-1][i-1], a[H-1][i]);
for(size_t i = 1; i < H; ++i) std::swap(a[H-i][W-1], a[H-i-1][W-1]);
for(size_t i = 1; i < W-1; ++i) std::swap(a[0][W-i], a[0][W-i-1]);
}
int main(){
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
std::cout<<"Orig. Matrix:\n"<<a;
rotate(a);
std::cout<<"Result Matrix:\n"<<a;
char b[4][4] = {{'a','b','c','d'},{'e','f','g','h'},{'i','j','k','l'},{'m','n','o','p'}};
std::cout<<b<<"\n";
rotate(b);
std::cout<<b<<"\n";
return 0;
}
Output:
Orig. Matrix:
1 2 3
4 5 6
7 8 9
Result Matrix:
4 1 2
7 5 3
8 9 6
a b c d
e f g h
i j k l
m n o p
e a b c
i f g d
m j k h
n o p l
/*Write code to rotate a square matrix:
Input:
1 2 3
4 5 6
7 8 9
Output:
4 1 2
7 5 3
8 9 6*/
public class MetricsRotation {
/**
*
*/
public MetricsRotation() {
}
public void rotate(int[][] metrics) throws InvalidArgumentException {
printMetrics(metrics);
if (metrics == null || metrics.length == 1) {
return;
}
int length = metrics.length;
for (int i = 0; i < length; i++) {
if (metrics[i] == null || length != metrics[i].length) {
throw new InvalidArgumentException(
"This is not a square metrics...");
}
}
rotate(metrics, 0, metrics.length);
System.out.println();
System.out.println("post rotation");
printMetrics(metrics);
return;
}
private void rotate(int[][] metrics, int level, int size) {
if (size <= 1) {
return;
}
int temp = metrics[level][level];
// left column rotation
for (int i = level; i < level + size - 1; i++) {
metrics[i][level] = metrics[i + 1][level];
}
// bottom row rotation
for (int i = level; i < level + size - 1; i++) {
metrics[level + size - 1][i] = metrics[level + size - 1][i + 1];
}
// right column rotation
for (int i = level + size - 1; i > level; i--) {
metrics[i][level + size - 1] = metrics[i - 1][level + size - 1];
}
// top row rotation
for (int i = level + size - 1; i > level + 1; i--) {
metrics[level][i] = metrics[level][i - 1];
}
metrics[level][level + 1] = temp;
rotate(metrics, level + 1, size - 2);
}
private void printMetrics(int[][] metrics) {
System.out.println("metircs printing ###############");
for (int row = 0; row < metrics.length; row++) {
System.out.println();
for (int col = 0; col < metrics[row].length; col++) {
System.out.print(metrics[row][col]);
System.out.print(" ");
}
}
}
/**
* @param args
* @throws InvalidArgumentException
*/
public static void main(String[] args) throws InvalidArgumentException {
int[][] metrics = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[][] metrics2 = { { 11, 12, 13, 14 }, { 15, 16, 17, 18 },
{ 19, 20, 21, 22 }, { 23, 24, 25, 26 } };
int[][] metrics3 = { { 1, 2 }, { 3, 4 } };
MetricsRotation metricsRotation = new MetricsRotation();
metricsRotation.rotate(metrics);
metricsRotation.rotate(metrics2);
metricsRotation.rotate(metrics3);
}
}
/**
*
*/
package com.interview;
/*Write code to rotate a square matrix:
Input:
1 2 3
4 5 6
7 8 9
Output:
4 1 2
7 5 3
8 9 6*/
public class MetricsRotation {
/**
*
*/
public MetricsRotation() {
}
public void rotate(int[][] metrics) throws InvalidArgumentException {
printMetrics(metrics);
if (metrics == null || metrics.length == 1) {
return;
}
int length = metrics.length;
for (int i = 0; i < length; i++) {
if (metrics[i] == null || length != metrics[i].length) {
throw new InvalidArgumentException(
"This is not a square metrics...");
}
}
rotate(metrics, 0, metrics.length);
System.out.println();
System.out.println("post rotation");
printMetrics(metrics);
return;
}
private void rotate(int[][] metrics, int level, int size) {
if (size <= 1) {
return;
}
int temp = metrics[level][level];
// left column rotation
for (int i = level; i < level + size - 1; i++) {
metrics[i][level] = metrics[i + 1][level];
}
// bottom row rotation
for (int i = level; i < level + size - 1; i++) {
metrics[level + size - 1][i] = metrics[level + size - 1][i + 1];
}
// right column rotation
for (int i = level + size - 1; i > level; i--) {
metrics[i][level + size - 1] = metrics[i - 1][level + size - 1];
}
// top row rotation
for (int i = level + size - 1; i > level + 1; i--) {
metrics[level][i] = metrics[level][i - 1];
}
metrics[level][level + 1] = temp;
rotate(metrics, level + 1, size - 2);
}
private void printMetrics(int[][] metrics) {
System.out.println("metircs printing ###############");
for (int row = 0; row < metrics.length; row++) {
System.out.println();
for (int col = 0; col < metrics[row].length; col++) {
System.out.print(metrics[row][col]);
System.out.print(" ");
}
}
}
/**
* @param args
* @throws InvalidArgumentException
*/
public static void main(String[] args) throws InvalidArgumentException {
int[][] metrics = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[][] metrics2 = { { 11, 12, 13, 14 }, { 15, 16, 17, 18 },
{ 19, 20, 21, 22 }, { 23, 24, 25, 26 } };
int[][] metrics3 = { { 1, 2 }, { 3, 4 } };
MetricsRotation metricsRotation = new MetricsRotation();
metricsRotation.rotate(metrics);
metricsRotation.rotate(metrics2);
metricsRotation.rotate(metrics3);
}
}
}
using System.IO;
using System;
using System.Text;
class Program
{
static void Main()
{
int size = 6;
int[,] matrix = new int[size, size];
Random rand = new Random();
// Randomly assign values to matrix
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
matrix[i,j] = rand.Next(100);
}
}
// Print matrix before reversal
Console.WriteLine("Before:");
Console.WriteLine(PrintMatrix(matrix, size));
// Reverse matrix
matrix = ReverseMatrix(matrix, size);
// Print matrix after reserval
Console.WriteLine("After:");
Console.WriteLine(PrintMatrix(matrix, size));
Console.WriteLine("Hello, World!");
}
static int[,] ReverseMatrix(int[,] matrix, int size){
int temp = 0;
int buffer = 0;
int iter = size / 2;
while(buffer < iter){
temp = matrix[size - 1 - buffer, buffer];
for(int i = size - 1 - buffer; i > buffer; i--){
matrix[i, buffer] = matrix[i-1, buffer];
}
for(int j = buffer; j < size - 1 - buffer; j++){
matrix[buffer, j] = matrix[buffer, j+1];
}
for(int i = buffer; i < size -1 - buffer; i++){
matrix[i , size - 1 - buffer] = matrix[i + 1, size - 1 - buffer];
}
for(int j = size - 1 - buffer; j > buffer + 1; j--){
matrix[size - 1 - buffer, j] = matrix[size- 1 - buffer, j - 1];
}
matrix[size- 1 - buffer, buffer + 1] = temp;
buffer++;
}
return matrix;
}
static string PrintMatrix(int[,] matrix, int size){
StringBuilder sb =new StringBuilder("");
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
sb.Append(matrix[j,i]).Append("\t");
}
sb.Append("\n");
}
return sb.ToString();
}
}
Here is a simplified C# code. Essentially we rotate each level recursively.
We calculate the minIndex and MaxIndex of the level. This makes writing the code for rotation very easy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Testyourskills
{
/// <summary>
/// Write code to rotate a square matrix:
/// </summary>
/// <author>Pramod Kumar Chandoria</author>
class RotateSquareArray
{
public static void Main(string[] arg)
{
int[,] a = new int[4,4] {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}};
Console.WriteLine("Printing array before rotate");
printArray(a);
rotateArray(a, 0, a.GetUpperBound(0) + 1);
Console.WriteLine("Printing array after rotate");
printArray(a);
a = new int[3, 3] { { 1, 2, 3}, { 4, 5, 6, }, { 7, 8, 9} };
Console.WriteLine("Printing array before rotate");
printArray(a);
rotateArray(a, 0, a.GetUpperBound(0) + 1);
Console.WriteLine("Printing array after rotate");
printArray(a);
}
private static void printArray(int[,] a)
{
for (int i = 0; i <= a.GetUpperBound(0); i++)
{
for (int j = 0; j <= a.GetUpperBound(1); j++)
{
Console.Write(a[i, j] < 10 ? " " : " ");
Console.Write(a[i, j]);
}
Console.WriteLine();
}
}
/// <summary>
///
/// </summary>
/// <param name="array">array in question to roate</param>
/// <param name="minIndex">minimum index of the level in question to rotate</param>
/// <param name="levelWidth">width of the level, essentially size of the square we are rotating</param>
internal static void rotateArray(int[,] array, int minIndex, int levelWidth)
{
if (levelWidth <= 1)
{
return;
}
int maxIndex = minIndex + levelWidth - 1;
// Rotate Left column
var topCorner = array[minIndex, minIndex];
for (int x = minIndex; x < maxIndex; x++ )
{
array[x, minIndex] = array[x + 1, minIndex];
}
// Rotate bottom Row
for (int y = minIndex; y < maxIndex; y++)
{
array[maxIndex, y] = array[maxIndex, y + 1];
}
// Rotate Right column
for (int x = maxIndex; x > minIndex; x--)
{
array[x, maxIndex] = array[x - 1, maxIndex];
}
// Rotate Top Row
for (int y = maxIndex; y > minIndex; y--)
{
array[minIndex, y] = array[minIndex, y - 1];
}
array[minIndex, minIndex + 1] = topCorner;
rotateArray(array, minIndex + 1, levelWidth - 2);
}
}
}
public class RotateSquareMatrix {
private static final int hi = 2;
private static final int lo = 0;
private int[][] matrix = new int[3][3];
{
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
matrix[1][2] = 6;
matrix[2][0] = 7;
matrix[2][1] = 8;
matrix[2][2] = 9;
}
public static void main(String[] args) {
RotateSquareMatrix sq = new RotateSquareMatrix();
System.out.println("Input:");
print(sq);
int i = 0, j = 0;
Direction d = Direction.right;
int val = sq.matrix[i][j];
while (d != Direction.stop) {
d = sq.findDirection(i, j, d);
switch (d) {
case left:
j--;
break;
case right:
j++;
break;
case top:
i--;
break;
case bottom:
i++;
break;
}
if (d != Direction.stop){
int temp = sq.matrix[i][j];
sq.matrix[i][j] = val;
val = temp;
}
}
System.out.println();
System.out.println("Output:");
print(sq);
}
static void print(RotateSquareMatrix sq) {
for (int k = 0; k < sq.matrix.length; k++) {
System.out.print(sq.matrix[k][0]);
System.out.print(" "+sq.matrix[k][1]);
System.out.println(" "+sq.matrix[k][2]);
}
}
private Direction findDirection(int i, int j, Direction curr) {
Direction d = curr;
if (curr == Direction.right && j == hi) {
d = Direction.bottom;
} else if (curr == Direction.bottom && i == hi) {
d = Direction.left;
} else if (curr == Direction.left && j == lo) {
d = Direction.top;
} else if (curr == Direction.top && i == lo) {
d = Direction.stop;
}
return d;
}
enum Direction {
left, right, top, bottom, stop
}
}
Input:
1 2 3
4 5 6
7 8 9
Output:
4 1 2
7 5 3
8 9 6
public class RotateMatrix {
public static void main(String[] args) {
System.out.println("Enter the Square Matirx size");
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
String[][] array = new String[size][size];
System.out.println("Enter the values in matrix");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
array[i][j] = scanner.next();
}
}
System.out.println("\n ");
System.out.println("=============================");
System.out.println("Matrix you have Entered\n");
System.out.println("=============================");
System.out.println("\n\n ");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println("\n");
}
String temp = array[0][0];
for (int i = 0; i <1; i++) {
for (int j = 1; j < size; j++) {
String value = array[i][j];
array[i][j]=temp;
temp=value;
}
for (int j = 1; j < size; j++) {
String value = array[j][size-1];
array[j][size-1]=temp;
temp=value;
}
for (int j = size-2; j >=0 ; j--) {
String value = array[size-1][j];
array[size-1][j]=temp;
temp=value;
}
for (int j = size-2; j >=0; j--) {
String value = array[j][i];
array[j][i]=temp;
temp=value;
}
}
System.out.println("=============================");
System.out.println("After rotating the Matrix \n");
System.out.println("=============================");
System.out.println("\n\n ");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println("\n");
}
}
}
public class RotateMatrix {
public static void main(String[] args) {
System.out.println("Enter the Square Matirx size");
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
String[][] array = new String[size][size];
System.out.println("Enter the values in matrix");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
array[i][j] = scanner.next();
}
}
System.out.println("\n ");
System.out.println("=============================");
System.out.println("Matrix you have Entered\n");
System.out.println("=============================");
System.out.println("\n\n ");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println("\n");
}
String temp = array[0][0];
for (int i = 0; i <1; i++) {
for (int j = 1; j < size; j++) {
String value = array[i][j];
array[i][j]=temp;
temp=value;
}
for (int j = 1; j < size; j++) {
String value = array[j][size-1];
array[j][size-1]=temp;
temp=value;
}
for (int j = size-2; j >=0 ; j--) {
String value = array[size-1][j];
array[size-1][j]=temp;
temp=value;
}
for (int j = size-2; j >=0; j--) {
String value = array[j][i];
array[j][i]=temp;
temp=value;
}
}
System.out.println("=============================");
System.out.println("After rotating the Matrix \n");
System.out.println("=============================");
System.out.println("\n\n ");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println("\n");
}
}
}
import java.util.Scanner;
public class RotateMatrix {
public static void main(String[] args) {
System.out.println("Enter the Square Matirx size");
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
String[][] array = new String[size][size];
System.out.println("Enter the values in matrix");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
array[i][j] = scanner.next();
}
}
System.out.println("\n ");
System.out.println("=============================");
System.out.println("Matrix you have Entered\n");
System.out.println("=============================");
System.out.println("\n\n ");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println("\n");
}
String temp = array[0][0];
for (int i = 0; i <1; i++) {
for (int j = 1; j < size; j++) {
String value = array[i][j];
array[i][j]=temp;
temp=value;
}
for (int j = 1; j < size; j++) {
String value = array[j][size-1];
array[j][size-1]=temp;
temp=value;
}
for (int j = size-2; j >=0 ; j--) {
String value = array[size-1][j];
array[size-1][j]=temp;
temp=value;
}
for (int j = size-2; j >=0; j--) {
String value = array[j][i];
array[j][i]=temp;
temp=value;
}
}
System.out.println("=============================");
System.out.println("After rotating the Matrix \n");
System.out.println("=============================");
System.out.println("\n\n ");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println("\n");
}
}
}
String temp = array[0][0];
for (int i = 0; i <1; i++) {
for (int j = 1; j < size; j++) {
String value = array[i][j];
array[i][j]=temp;
temp=value;
}
for (int j = 1; j < size; j++) {
String value = array[j][size-1];
array[j][size-1]=temp;
temp=value;
}
for (int j = size-2; j >=0 ; j--) {
String value = array[size-1][j];
array[size-1][j]=temp;
temp=value;
}
for (int j = size-2; j >=0; j--) {
String value = array[j][i];
array[j][i]=temp;
temp=value;
}
}
No soln here gives a completely rotated matrix for 4*4
if i/p is:
10 20 5 5
22 33 4 10
2 6 8 9
55 11 66 7
o/p should be:
22 10 20 5
2 6 33 5
55 8 4 10
11 66 7 9
#include <stdio.h>
#include <string.h>
int main()
{
int m[10][10],n,i,j,k,l,p,row_min=0,col_min=0,row_max,col_max,temp;
char choice[4];
scanf("%d",&n); //input no of elements
scanf("%s",choice); //enter the choice whether "CW"(Clockwise) or "CCW"(Counter Clockwise)
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&m[i][j]); //enter the elements
}
}
l=n/2; //count how many times the while loop will run
row_max=col_max=n;
if(strcmp(choice,"CW")==0) //if it is clockwise
{
while(l>0)
{
temp=m[row_min][col_min];
//left
for(i=col_min;i<col_max-1;i++)
m[i][col_min]=m[i+1][col_min];
//lower
k=row_max-1;
for(i=row_min;i<row_max-1;i++)
m[k][i]=m[k][i+1];
//right
p=col_max-1;
for(i=col_max-1;i>0;i--)
m[i][p]=m[i-1][p];
//upper
for(i=row_max-1;i>1;i--)
m[row_min][i]=m[row_min][i-1];
m[row_min][row_min+1]=temp;
l--;
row_max--;
col_max--;
row_min++;
col_min++;
}
}
else if(strcmp(choice,"CCW")==0) //if it is anticlockwise rotation
{
while(l>0)
{
temp=m[row_min][col_min];
//upper
for(i=row_min;i<row_max-1;i++)
m[row_min][i]=m[row_min][i+1];
//right
p=col_max-1;
for(i=col_min;i<col_max-1;i++)
m[i][p]=m[i+1][p];
//bottom
k=row_max-1;
for(i=row_max-1;i>0;i--)
m[k][i]=m[k][i-1];
//left
for(i=col_max-1;i>1;i--)
m[i][col_min]=m[i-1][col_min];
//upper
m[col_min+1][col_min]=temp;
l--;
row_max--;
col_max--;
row_min++;
col_min++;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",m[i][j]);
}
//printf("\n");
}
return 0;
}
#include <stdio.h>
#include <string.h>
int main()
{
int m[10][10],n,i,j,k,l,p,row_min=0,col_min=0,row_max,col_max,temp;
char choice[4];
scanf("%d",&n); //input no of elements
scanf("%s",choice); //enter the choice whether "CW"(Clockwise) or "CCW"(Counter Clockwise)
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&m[i][j]); //enter the elements
}
}
l=n/2; //count how many times the while loop will run
row_max=col_max=n;
if(strcmp(choice,"CW")==0) //if it is clockwise
{
while(l>0)
{
temp=m[row_min][col_min];
//left
for(i=col_min;i<col_max-1;i++)
m[i][col_min]=m[i+1][col_min];
//lower
k=row_max-1;
for(i=row_min;i<row_max-1;i++)
m[k][i]=m[k][i+1];
//right
p=col_max-1;
for(i=col_max-1;i>0;i--)
m[i][p]=m[i-1][p];
//upper
for(i=row_max-1;i>1;i--)
m[row_min][i]=m[row_min][i-1];
m[row_min][row_min+1]=temp;
l--;
row_max--;
col_max--;
row_min++;
col_min++;
}
}
else if(strcmp(choice,"CCW")==0) //if it is anticlockwise rotation
{
while(l>0)
{
temp=m[row_min][col_min];
//upper
for(i=row_min;i<row_max-1;i++)
m[row_min][i]=m[row_min][i+1];
//right
p=col_max-1;
for(i=col_min;i<col_max-1;i++)
m[i][p]=m[i+1][p];
//bottom
k=row_max-1;
for(i=row_max-1;i>0;i--)
m[k][i]=m[k][i-1];
//left
for(i=col_max-1;i>1;i--)
m[i][col_min]=m[i-1][col_min];
//upper
m[col_min+1][col_min]=temp;
l--;
row_max--;
col_max--;
row_min++;
col_min++;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",m[i][j]);
}
//printf("\n");
}
return 0;
}
static int[,] rotateMatrix90Clockwise(int[,] oldMatrix)
{
int[,] newMatrix = new int[oldMatrix.GetLength(1), oldMatrix.GetLength(0)];
int newRow = oldMatrix.GetLength(1) - 1;
int newColumn = 0;
for (int i = 0; i < oldMatrix.GetLength(1);i++)
{
for (int j = 0; j < oldMatrix.GetLength(0); j++)
{
newMatrix[i, j] = oldMatrix[newRow--, newColumn];
}
newColumn += 1;
newRow = oldMatrix.GetLength(1) - 1;
}
return newMatrix;
}
static int[,] rotateMatrix90Clockwise(int[,] oldMatrix)
{
int[,] newMatrix = new int[oldMatrix.GetLength(1), oldMatrix.GetLength(0)];
int newRow = oldMatrix.GetLength(1) - 1;
int newColumn = 0;
for (int i = 0; i < oldMatrix.GetLength(1);i++)
{
for (int j = 0; j < oldMatrix.GetLength(0); j++)
{
newMatrix[i, j] = oldMatrix[newRow--, newColumn];
}
newColumn += 1;
newRow = oldMatrix.GetLength(1) - 1;
}
return newMatrix;
}
private static int[,] rotateMatrix90Clockwise(int[,] oldMatrix)
{
int[,] newMatrix = new int[oldMatrix.GetLength(1), oldMatrix.GetLength(0)];
int newRow = oldMatrix.GetLength(1) - 1;
int newColumn = 0;
for (int i = 0; i < oldMatrix.GetLength(1);i++)
{
for (int j = 0; j < oldMatrix.GetLength(0); j++)
{
newMatrix[i, j] = oldMatrix[newRow--, newColumn];
}
newColumn += 1;
newRow = oldMatrix.GetLength(1) - 1;
}
return newMatrix;
}
Assuming MXN matrix... and this solution works in C#
private static int[,] RotateMatrixCounterClockwise(int[,] oldMatrix)
{
int[,] newMatrix = new int[oldMatrix.GetLength(1), oldMatrix.GetLength(0)];
int newRow = oldMatrix.GetLength(1) - 1;
int newColumn = 0;
for (int i = 0; i < oldMatrix.GetLength(1);i++)
{
for (int j = 0; j < oldMatrix.GetLength(0); j++)
{
newMatrix[i, j] = oldMatrix[newRow--, newColumn];
}
newColumn += 1;
newRow = oldMatrix.GetLength(1) - 1;
}
return newMatrix;
}
Assuming a square matrix
- Omri.Bashari May 04, 2015