Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- namespace Spiral
- {
- class Program
- {
- static bool IsFree(int[,] b, int i, int j)
- {
- int n = b.GetLength(0);
- int m = b.GetLength(1);
- if (i < 0 || i >= n || j < 0 || j >= m)
- {
- return false;
- }
- else if (b[i, j] != 0)
- {
- return false;
- }
- return true;
- }
- static List<int> SpiralTraverse(int[,] a)
- {
- List<int> nums = new List<int>();
- int[,] b = new int[a.GetLength(0), a.GetLength(1)];
- int i = 0;
- int j = 0;
- int rounds = Math.Min(a.GetLength(0), a.GetLength(1)) / 2;
- for (int k = 0; k <= rounds; k++)
- {
- while(IsFree(b, i, j))
- {
- nums.Add(a[i, j]);
- b[i, j] = 1;
- j++; // right
- }
- i++;
- j--;
- while (IsFree(b, i, j))
- {
- nums.Add(a[i, j]);
- b[i, j] = 1;
- i++; // down
- }
- i--;
- j--;
- while (IsFree(b, i, j))
- {
- nums.Add(a[i, j]);
- b[i, j] = 1;
- j--; // left
- }
- i--;
- j++;
- while (IsFree(b, i, j))
- {
- nums.Add(a[i, j]);
- b[i, j] = 1;
- i--; // up
- }
- i++;
- j++;
- }
- return nums;
- }
- static void Main(string[] args)
- {
- int[,] matrix = { { 1, 2, 3, 4, 5 },
- { 6, 7, 8, 9, 10 },
- { 11, 12, 13, 14, 15 },
- { 16, 17, 18, 19, 20 },
- { 21, 22, 23, 24, 25 }};
- List<int> spiral = SpiralTraverse(matrix);
- foreach (var item in spiral)
- {
- Console.Write($"{item} ");
- }
- Console.WriteLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement