Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Given a 2D matrix of dimension m x n and a positive integer r,
- // rotate the matrix r times and print the resultant matrix.
- // Rotation should be in anti-clockwise direction.
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- class Solution {
- static void printMatrix(int[,] matrix) {
- int row_cnt = matrix.GetLength(0);
- int col_cnt = matrix.GetLength(1);
- for (int row = 0; row < row_cnt; row++) {
- for (int col = 0; col < col_cnt; col++) {
- Console.Write(matrix[row,col] + " ");
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- }
- static void matrixRotation(int[][] matrix, int rotates) {
- int row_cnt = matrix.Length;
- int col_cnt = matrix[0].Length;
- int[,] output = new int[row_cnt, col_cnt];
- for (int row = 0; row < row_cnt; row++) {
- for (int col = 0; col < col_cnt; col++) {
- // compute row/col grid location
- // 0,0 0,1 0,1 0,0
- // 1,0 1,1 1,1 1,0 => 0000
- // 1,0 1,1 1,1 1,0 0110
- // 0,0 0,1 0,1 0,0 0000
- int row_pos = Math.Min(row, (row_cnt - 1) - row);
- int col_pos = Math.Min(col, (col_cnt - 1) - col);
- // get the relative "ring" depth
- int ring = Math.Min(row_pos, col_pos);
- // get the "ring" row/col sizes
- int ring_row_cnt = (row_cnt - 1) - ring;
- int ring_col_cnt = (col_cnt - 1) - ring;
- int out_row = row;
- int out_col = col;
- for (int i = 0; i < rotates; i++) {
- // left side -> move down
- if (out_col == ring && out_row < ring_row_cnt) {
- out_row++;
- }
- // right side -> move up
- else if (out_col == ring_col_cnt && out_row > ring) {
- out_row--;
- }
- // top side -> move left
- else if (out_col > ring && out_row == ring) {
- out_col--;
- }
- // bottom side -> move right
- else if (out_col < ring_col_cnt && out_row == ring_row_cnt) {
- out_col++;
- }
- }
- //Console.WriteLine(out_row + " " + out_col);
- output[out_row, out_col] = matrix[row][col];
- }
- }
- printMatrix(output);
- }
- static void Main(String[] args) {
- string[] tokens_m = Console.ReadLine().Split(' ');
- int m = Convert.ToInt32(tokens_m[0]);
- int n = Convert.ToInt32(tokens_m[1]);
- int r = Convert.ToInt32(tokens_m[2]);
- int[][] matrix = new int[m][];
- for(int matrix_i = 0; matrix_i < m; matrix_i++){
- string[] matrix_temp = Console.ReadLine().Split(' ');
- matrix[matrix_i] = Array.ConvertAll(matrix_temp,Int32.Parse);
- }
- matrixRotation(matrix, r);
- }
- }
Add Comment
Please, Sign In to add comment