aluin

Untitled

Dec 7th, 2013
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. using System;
  2.  
  3. class SpiralArray
  4. {
  5. /*Използваме двумерен масив (таблица на повече от един ред, индексация и на колоните и на редовете)*/
  6.  
  7. static void Main()
  8. {
  9. Console.Write("Enter a number:\nN = ");
  10. int number = int.Parse(Console.ReadLine());
  11.  
  12. // Инициализираме нов масив
  13. int[,] spiral = new int[number,number];
  14.  
  15. string direction = "right";
  16. int currentRow = 0;
  17. int currentCol = 0;
  18.  
  19. //текущия елемент
  20. for (int i = 1; i <= number*number; i++)
  21. {
  22. // смяна на посоката
  23. if (direction == "right" && (currentCol >= number || spiral[currentRow, currentCol] != 0)) //с проверка за попълнено поле
  24. {
  25. currentCol--;
  26. currentRow++;
  27. direction = "down";
  28. }
  29. else if (direction == "down" && (currentRow >= number || spiral[currentRow, currentCol] != 0))
  30. {
  31. currentCol--;
  32. currentRow--;
  33. direction = "left";
  34. }
  35. else if (direction == "left" && (currentCol < 0 || spiral[currentRow, currentCol] != 0))
  36. {
  37. currentCol++;
  38. currentRow--;
  39. direction = "up";
  40. }
  41. else if (direction == "up" && (currentRow < 0 || spiral[currentRow, currentCol] != 0))
  42. {
  43. currentCol++;
  44. currentRow++;
  45. direction = "right";
  46. }
  47.  
  48. //Движение по клетките
  49. spiral[currentRow, currentCol] = i;
  50. if (direction == "right")
  51. {
  52. currentCol++;
  53. }
  54. else if (direction == "down")
  55. {
  56. currentRow++;
  57. }
  58. else if (direction == "left")
  59. {
  60. currentCol--;
  61. }
  62. else if (direction == "up")
  63. {
  64. currentRow--;
  65. }
  66. }
  67.  
  68. //print matrix
  69. for (int i = 0; i < number; i++)
  70. {
  71. for (int j = 0; j < number; j++)
  72. {
  73. Console.Write(spiral[i,j] + " ");
  74. }
  75. Console.WriteLine();
  76. }
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment