Guest User

Untitled

a guest
May 25th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.06 KB | None | 0 0
  1. // Given a 2D matrix of dimension m x n and a positive integer r,
  2. // rotate the matrix r times and print the resultant matrix.
  3. // Rotation should be in anti-clockwise direction.
  4.  
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. class Solution {
  10.  
  11. static void printMatrix(int[,] matrix) {
  12. int row_cnt = matrix.GetLength(0);
  13. int col_cnt = matrix.GetLength(1);
  14. for (int row = 0; row < row_cnt; row++) {
  15. for (int col = 0; col < col_cnt; col++) {
  16. Console.Write(matrix[row,col] + " ");
  17. }
  18. Console.WriteLine();
  19. }
  20. Console.WriteLine();
  21. }
  22.  
  23. static void matrixRotation(int[][] matrix, int rotates) {
  24. int row_cnt = matrix.Length;
  25. int col_cnt = matrix[0].Length;
  26.  
  27. int[,] output = new int[row_cnt, col_cnt];
  28.  
  29. for (int row = 0; row < row_cnt; row++) {
  30. for (int col = 0; col < col_cnt; col++) {
  31.  
  32. // compute row/col grid location
  33. // 0,0 0,1 0,1 0,0
  34. // 1,0 1,1 1,1 1,0 => 0000
  35. // 1,0 1,1 1,1 1,0 0110
  36. // 0,0 0,1 0,1 0,0 0000
  37. int row_pos = Math.Min(row, (row_cnt - 1) - row);
  38. int col_pos = Math.Min(col, (col_cnt - 1) - col);
  39. // get the relative "ring" depth
  40. int ring = Math.Min(row_pos, col_pos);
  41. // get the "ring" row/col sizes
  42. int ring_row_cnt = (row_cnt - 1) - ring;
  43. int ring_col_cnt = (col_cnt - 1) - ring;
  44.  
  45. int out_row = row;
  46. int out_col = col;
  47. for (int i = 0; i < rotates; i++) {
  48. // left side -> move down
  49. if (out_col == ring && out_row < ring_row_cnt) {
  50. out_row++;
  51. }
  52. // right side -> move up
  53. else if (out_col == ring_col_cnt && out_row > ring) {
  54. out_row--;
  55. }
  56. // top side -> move left
  57. else if (out_col > ring && out_row == ring) {
  58. out_col--;
  59. }
  60. // bottom side -> move right
  61. else if (out_col < ring_col_cnt && out_row == ring_row_cnt) {
  62. out_col++;
  63. }
  64. }
  65. //Console.WriteLine(out_row + " " + out_col);
  66. output[out_row, out_col] = matrix[row][col];
  67. }
  68. }
  69. printMatrix(output);
  70. }
  71.  
  72. static void Main(String[] args) {
  73. string[] tokens_m = Console.ReadLine().Split(' ');
  74. int m = Convert.ToInt32(tokens_m[0]);
  75. int n = Convert.ToInt32(tokens_m[1]);
  76. int r = Convert.ToInt32(tokens_m[2]);
  77. int[][] matrix = new int[m][];
  78. for(int matrix_i = 0; matrix_i < m; matrix_i++){
  79. string[] matrix_temp = Console.ReadLine().Split(' ');
  80. matrix[matrix_i] = Array.ConvertAll(matrix_temp,Int32.Parse);
  81. }
  82. matrixRotation(matrix, r);
  83. }
  84. }
Add Comment
Please, Sign In to add comment