private static int[,] FillMatrix(int[,] matrix, IDirection direction) { int number = 1; int currentRow = 0; int currentColumn = 0; int nextRow = 0; int nextColumn = 0; while (number <= matrix.Length) { nextRow = currentRow + direction.Row; nextColumn = currentColumn + direction.Column; matrix[currentRow, currentColumn] = number; number++; bool hasEmptyCell = false; for (int i = 0; i < direction.DirectionsCount; i++) { if (!CheckisEmptyNextCell(matrix, nextRow, nextColumn)) { direction.ChangeDirection(); nextRow = currentRow + direction.Row; nextColumn = currentColumn + direction.Column; } else { currentRow = nextRow; currentColumn = nextColumn; hasEmptyCell = true; break; } } if (!hasEmptyCell) { int[] coord = FindEmptyCell(matrix); currentRow = coord[0]; currentColumn = coord[1]; } } return(matrix); }