mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-08 18:49:07 +01:00
47 lines
1,010 B
C#
47 lines
1,010 B
C#
|
using System;
|
||
|
|
||
|
public class SnailSolution {
|
||
|
private static void Update(ref int dx, ref int dy) {
|
||
|
int newDx = -dy, newDy = dx;
|
||
|
dy = newDy;
|
||
|
dx = newDx;
|
||
|
}
|
||
|
|
||
|
public static int[] Snail(int[][] array) {
|
||
|
if (array.Length == 1 && array[0].Length == 0) {
|
||
|
return new int[] {};
|
||
|
}
|
||
|
|
||
|
int[] result = new int[array.Length * array.Length];
|
||
|
|
||
|
int y = 0, x = 0;
|
||
|
int dy = 0, dx = 1;
|
||
|
|
||
|
int left = -1, right = array.Length;
|
||
|
int top = 0, bottom = array.Length;
|
||
|
|
||
|
for (var i = 0; i < result.Length; i++) {
|
||
|
result[i] = array[y][x];
|
||
|
|
||
|
if (dx != 0 && x + dx <= left) {
|
||
|
left++;
|
||
|
Update(ref dx, ref dy);
|
||
|
} else if (dx != 0 && x + dx >= right) {
|
||
|
right--;
|
||
|
Update(ref dx, ref dy);
|
||
|
} else if (dy != 0 && y + dy <= top) {
|
||
|
top++;
|
||
|
Update(ref dx, ref dy);
|
||
|
} else if (dy != 0 && y + dy >= bottom) {
|
||
|
bottom--;
|
||
|
Update(ref dx, ref dy);
|
||
|
}
|
||
|
|
||
|
x += dx;
|
||
|
y += dy;
|
||
|
}
|
||
|
|
||
|
return result;
|
||
|
}
|
||
|
}
|