Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.33 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace _54.Spiral_Matrix
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13.  
  14. /* int[][] matrix = new int[3][];
  15.  
  16. matrix[0] = new int[3] { 1, 2, 3 };
  17. matrix[1] = new int[3] { 4, 5, 6 };
  18. matrix[2] = new int[3] { 7, 8, 9 };*/
  19. int[][] matrix = new int[3][];
  20.  
  21. matrix[0] = new int[4] { 1, 2, 3, 4 };
  22. matrix[1] = new int[4] { 5, 6, 7, 8 };
  23. matrix[2] = new int[4] { 9, 10, 11, 12 };
  24.  
  25. var result = SpiralOrder(matrix);
  26.  
  27. foreach (var item in result)
  28. {
  29. Console.Write($"{item} ");
  30. }
  31.  
  32. Console.Read();
  33. }
  34.  
  35. public static IList<int> SpiralOrder(int[][] matrix)
  36. {
  37. if (matrix == null)
  38. return null;
  39.  
  40. IList<int> spiral = new List<int>();
  41.  
  42. int maxRows = matrix.Length;
  43.  
  44. if (maxRows == 0)
  45. {
  46. return spiral;
  47. }
  48.  
  49. int maxColumns = matrix[0].Length;
  50. int maxSize = maxRows * maxColumns;
  51. int startColumn = 0;
  52. int startRow = 0;
  53. int currentColumn = 0;
  54. int currentRow = 0;
  55.  
  56. int count = 0;
  57.  
  58. int rightDirection = 1;
  59. int downDirection = 0;
  60.  
  61. while (count < maxSize)
  62. {
  63. spiral.Add(matrix[currentRow][currentColumn]);
  64.  
  65. if (rightDirection == 1 && downDirection == 0)
  66. {
  67. currentColumn++;
  68.  
  69. if (currentColumn >= maxColumns)
  70. {
  71. currentColumn--;
  72. maxColumns--;
  73. currentRow++;
  74. startRow++;
  75.  
  76. downDirection = 1;
  77. rightDirection = 0;
  78. }
  79. }
  80. else if (rightDirection == 0 && downDirection == 1)
  81. {
  82. currentRow++;
  83.  
  84. if (currentRow >= maxRows)
  85. {
  86. currentRow--;
  87. maxRows--;
  88. currentColumn--;
  89.  
  90. downDirection = 0;
  91. rightDirection = -1;
  92. }
  93. }
  94. else if (rightDirection == -1 && downDirection == 0)
  95. {
  96. currentColumn--;
  97.  
  98. if (currentColumn < startColumn)
  99. {
  100. currentRow--;
  101. currentColumn++;
  102.  
  103. downDirection = -1;
  104. rightDirection = 0;
  105. }
  106. }
  107. else if (rightDirection == 0 && downDirection == -1)
  108. {
  109. currentRow--;
  110.  
  111. if (currentRow < startRow)
  112. {
  113. currentRow++;
  114. startColumn++;
  115. currentColumn++;
  116.  
  117. downDirection = 0;
  118. rightDirection = 1;
  119. }
  120. }
  121.  
  122. count++;
  123. }
  124.  
  125. return spiral;
  126. }
  127. }
  128. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement