Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace _54.Spiral_Matrix
- {
- class Program
- {
- static void Main(string[] args)
- {
- /* int[][] matrix = new int[3][];
- matrix[0] = new int[3] { 1, 2, 3 };
- matrix[1] = new int[3] { 4, 5, 6 };
- matrix[2] = new int[3] { 7, 8, 9 };*/
- int[][] matrix = new int[3][];
- matrix[0] = new int[4] { 1, 2, 3, 4 };
- matrix[1] = new int[4] { 5, 6, 7, 8 };
- matrix[2] = new int[4] { 9, 10, 11, 12 };
- var result = SpiralOrder(matrix);
- foreach (var item in result)
- {
- Console.Write($"{item} ");
- }
- Console.Read();
- }
- public static IList<int> SpiralOrder(int[][] matrix)
- {
- if (matrix == null)
- return null;
- IList<int> spiral = new List<int>();
- int maxRows = matrix.Length;
- if (maxRows == 0)
- {
- return spiral;
- }
- int maxColumns = matrix[0].Length;
- int maxSize = maxRows * maxColumns;
- int startColumn = 0;
- int startRow = 0;
- int currentColumn = 0;
- int currentRow = 0;
- int count = 0;
- int rightDirection = 1;
- int downDirection = 0;
- while (count < maxSize)
- {
- spiral.Add(matrix[currentRow][currentColumn]);
- if (rightDirection == 1 && downDirection == 0)
- {
- currentColumn++;
- if (currentColumn >= maxColumns)
- {
- currentColumn--;
- maxColumns--;
- currentRow++;
- startRow++;
- downDirection = 1;
- rightDirection = 0;
- }
- }
- else if (rightDirection == 0 && downDirection == 1)
- {
- currentRow++;
- if (currentRow >= maxRows)
- {
- currentRow--;
- maxRows--;
- currentColumn--;
- downDirection = 0;
- rightDirection = -1;
- }
- }
- else if (rightDirection == -1 && downDirection == 0)
- {
- currentColumn--;
- if (currentColumn < startColumn)
- {
- currentRow--;
- currentColumn++;
- downDirection = -1;
- rightDirection = 0;
- }
- }
- else if (rightDirection == 0 && downDirection == -1)
- {
- currentRow--;
- if (currentRow < startRow)
- {
- currentRow++;
- startColumn++;
- currentColumn++;
- downDirection = 0;
- rightDirection = 1;
- }
- }
- count++;
- }
- return spiral;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement