1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-25 10:11:56 +01:00
CodeWars/4kyu/snail/solution.cs

47 lines
1,010 B
C#
Raw Normal View History

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;
}
}