Array Algorithm: Rotate an image

Solution

var top = matrix[layer][i];
var right = matrix[i][length - layer];
var bot = matrix[length - layer][length -i];
var left = matrix[length - i][layer];
  • Top will be fixed the row, only the column moving by i
  • Right fixed by the column, only the row moving by i
  • Bottom fixed by the row, opposite of the top
  • Left fixed by the column, opposite of the right
// top = left
matrix[layer][i] = left;
// right = top
matrix[i][length - layer] = top;
// bot = right
matrix[length - layer][length - i] = right;
// left = bot
matrix[length - i][layer] = bot;
public class Solution {
public void Rotate(int[][] matrix) {
var layers = matrix.Length / 2;
var length = matrix.Length - 1;

for(var layer = 0; layer < layers; layer++){

for(var i = layer; i < length - layer; i++){
var top = matrix[layer][i];
var right = matrix[i][length - layer];
var bot = matrix[length - layer][length -i];
var left = matrix[length - i][layer];

// top = left
matrix[layer][i] = left;
// right = top
matrix[i][length - layer] = top;
// bot = right
matrix[length - layer][length - i] = right;
// left = bot
matrix[length - i][layer] = bot;
}
}
}
}

--

--

--

Software Engineer who is highly interested in building high scalability systems.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Unity: Creating thruster function

GSSOC : Open Source….a journey not a destination..!!

Building a secure PST cross-chain verification system

I am a Japanese Software Engineer.

Data Pipeline Solution — Part 2

Distributed Tracing with Azure Spring Cloud and Azure Application Insights

Aligned Dev Blog

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Finn Nguyen

Finn Nguyen

Software Engineer who is highly interested in building high scalability systems.

More from Medium

Add Two Number 📯

What should developers have to know about Timezones?

3rd Maximum in an Array

How to write robust REST API with OpenAPI