Advertisement
Guest User

Untitled

a guest
May 14th, 2016
315
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 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 SpiralMatrix
  8. {
  9. class SpiralMatrix
  10. {
  11. static void Main(string[] args)
  12. {
  13. Console.Write("Enter number: ");
  14. int n = int.Parse(Console.ReadLine());
  15. int[,] matrix = new int[n, n];
  16. int row = 0;
  17. int col = 0;
  18. string direction = "right";
  19. int maxRotations = n * n;
  20.  
  21. for (int i = 1; i < maxRotations; i++)
  22. {
  23. if (direction == "right" && ((col > n - 1) || matrix[row, col] != 0))
  24. {
  25. direction = "down";
  26. col--;
  27. row++;
  28. }
  29. if (direction == "down" && ((row > n - 1) || matrix[row, col] != 0))
  30. {
  31. direction = "left";
  32. row--;
  33. col--;
  34. }
  35. if (direction == "left" && ((col < 0) || matrix[row, col] != 0))
  36. {
  37. direction = "up";
  38. col++;
  39. row--;
  40. }
  41. if (direction == "up" && ((row > 0) || matrix[row, col] != 0))
  42. {
  43. direction = "right";
  44. col++;
  45. row++;
  46. }
  47. matrix[row, col] = i;
  48. if (direction == "right")
  49. {
  50. col++;
  51. }
  52. if (direction == "down")
  53. {
  54. row++;
  55. }
  56. if (direction == "left")
  57. {
  58. col--;
  59. }
  60. if (direction == "up")
  61. {
  62. row--;
  63. }
  64. }
  65. for (int i = 0; i < n; i++)
  66. {
  67. for (int j = 0; j < n; j++)
  68. {
  69. Console.Write("{0,4}", matrix[i, j]);
  70. }
  71. Console.WriteLine();
  72. }
  73. }
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement