Advertisement
Kolimnared

Spiral Matrix

Oct 21st, 2014
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. using System;
  2.  
  3. class SpiralMatrix
  4. {
  5. private static void ChangeDir(ref string dir) {
  6. if (dir == "Right"){
  7. dir = "Down";
  8. }else if (dir == "Down") {
  9. dir = "Left";
  10. }else if(dir == "Left"){
  11. dir = "Up";
  12. }else{
  13. dir = "Right";
  14. }
  15. }
  16.  
  17. static void Main(string[] args)
  18. {
  19. int n = int.Parse(Console.ReadLine());
  20.  
  21. int top = 0;
  22. int left = 0;
  23. int bottom = n - 1;
  24. int right = n - 1;
  25. int counter = 1;
  26. string dir = "Right";
  27. int[,] arr = new int[n,n];
  28.  
  29. while (top <= bottom && left <= right)
  30. {
  31. if (dir == "Right") {
  32. for (int i = left; i <= right; i++)
  33. {
  34. arr[top, i] = counter++;
  35. }
  36. top++;
  37. ChangeDir(ref dir);
  38. }
  39. else if (dir == "Down") {
  40. for (int i = top; i <= bottom; i++)
  41. {
  42. arr[i, right] = counter++;
  43. }
  44. right--;
  45. ChangeDir(ref dir);
  46. }
  47. else if (dir == "Left"){
  48. for (int i = right; i >= left; i--)
  49. {
  50. arr[bottom, i] = counter++;
  51. }
  52. bottom--;
  53. ChangeDir(ref dir);
  54. }
  55. else {
  56. for (int i = bottom; i >= top; i--)
  57. {
  58. arr[i, left] = counter++;
  59. }
  60. left++;
  61. ChangeDir(ref dir);
  62. }
  63. }
  64.  
  65. for (int i = 0; i < n; i++){
  66. for (int j = 0; j < n; j++) {
  67. Console.Write("{0} ", arr[i,j].ToString().PadRight(3, ' '));
  68. }
  69. Console.WriteLine();
  70. }
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement