Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static int[] Razmotat(int[,] a)
- {
- var n = a.GetLength(0); // Matrix is n*n
- var result = new int[a.Length]; // 1d array of length n*n
- var p = 0; //processed elements
- //start coords (right bottom)
- int i = n - 1;
- int j = 0;
- //bounds to know where to stop on each circle
- int leftBound = 0;
- int rightBound = n - 1;
- int topBound = 0;
- int bottomBound = n - 1;
- //moving direction
- var dir = Direction.Up;
- //while current element is not center
- for(int k = 0; k < result.Length; k++)
- {
- switch (dir)
- {
- //UP
- case Direction.Up:
- result[p++] = a[i, j]; //save current element to result
- if (i == topBound) //if it's bound then change direction, move index to next and change bound
- {
- dir = Direction.Right;
- j++;
- leftBound++;
- }
- else //else go to next element in same direction
- i--;
- break;
- //RIGHT
- case Direction.Right:
- result[p++] = a[i, j];
- if (j == rightBound)
- {
- dir = Direction.Down;
- i++;
- topBound++;
- }
- else
- j++;
- break;
- case Direction.Down:
- result[p++] = a[i, j];
- if (i == bottomBound)
- {
- dir = Direction.Left;
- j--;
- rightBound--;
- }
- else
- i++;
- break;
- case Direction.Left:
- result[p++] = a[i, j];
- if (j == leftBound)
- {
- dir = Direction.Up;
- i--;
- bottomBound--;
- }
- else
- j--;
- break;
- }
- }
- //reverse
- for (int k = 0; k < result.Length / 2; k++)
- {
- int tmp = result[k];
- result[k] = result[result.Length - k - 1];
- result[result.Length - k - 1] = tmp;
- }
- return result;
- }
- enum Direction
- {
- Up,
- Down,
- Left,
- Right
- }
Add Comment
Please, Sign In to add comment