Advertisement
Guest User

Untitled

a guest
May 23rd, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. using System;
  2.  
  3. class Solution
  4. {
  5. // Spiral array -
  6. public static void Main()
  7. {
  8. var testcase = new int[4][];
  9. testcase[0] = new int[] {1, 2, 3, 4 };
  10. testcase[1] = new int[] {12, 13, 14, 5 };
  11. testcase[2] = new int[] {11, 16, 15, 6 };
  12. testcase[3] = new int[] {10, 9, 8, 7 };
  13.  
  14. testcase = new int[1][];
  15. testcase[0] = new int[] { 1 };
  16.  
  17. var result = SpiralCopy(testcase);
  18. }
  19.  
  20. public static int[] SpiralCopy(int[][] matrix)
  21. {
  22. int rows = matrix.Length;
  23. int cols = matrix[0].Length;
  24.  
  25. int total = rows * cols;
  26. var spiral = new int[total];
  27.  
  28. int index = 0;
  29.  
  30. int leftCol = 0;
  31. int rightCol = cols - 1;
  32. int topRow = 0;
  33. int bottomRow = rows - 1;
  34.  
  35. // the idea is to simplify the while loop - one variable checking, check the length
  36. // of spiral array intead of compared to the start position of spiral layer.
  37. while (index < total)
  38. {
  39. // top row - go right,
  40. for (int col = leftCol; col <= rightCol; col++)
  41. {
  42. var current = matrix[topRow][col];
  43. spiral[index++] = current;
  44. }
  45.  
  46. // right col - go down
  47. for (int row = topRow + 1; row <= bottomRow; row++)
  48. {
  49. var current = matrix[row][rightCol];
  50. spiral[index++] = current;
  51. }
  52.  
  53. // go left
  54. if (topRow == bottomRow) // added after the mocking, 5/23/2017
  55. {
  56. continue;
  57. }
  58.  
  59. for (int col = rightCol - 1; col >= leftCol; col--)
  60. {
  61. var current = matrix[bottomRow][col];
  62. spiral[index++] = current;
  63. }
  64.  
  65. // go up
  66. if (leftCol == rightCol) // added after the mocking, 5/23/2017
  67. {
  68. continue;
  69. }
  70.  
  71. for (int row = bottomRow - 1; row > topRow; row--)
  72. {
  73. var current = matrix[row][leftCol];
  74. spiral[index++] = current;
  75. }
  76.  
  77. leftCol++;
  78. rightCol--;
  79. topRow++;
  80. bottomRow--;
  81. }
  82.  
  83. return spiral;
  84. }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement