Medium

Construct a square matrix with a size N × N containing integers from 1 to N * N in a spiral order, starting from top-left and in clockwise direction.

Example

For n = 3, the output should be

spiralNumbers(n) = [[1, 2, 3],

                                          [8, 9, 4],

                                          [7, 6, 5]]

Input/Output

  • [execution time limit] 0.5 seconds (c)

  • [input] integer n

    Matrix size, a positive integer.

    Guaranteed constraints:
    3 ≤ n ≤ 100.

  • [output] array.array.integer

[C] Syntax Tips

// Prints help message to the console
// Returns a string
char * helloWorld(char * name) {
    char * answer = malloc(strlen(name) + 8);
    printf("This prints to the console when you Run Tests");
    strcpy(answer, "Hello, ");
    strcat(answer, name);
    return answer;
}

더보기

Solution

// Arrays are already defined with this interface:
// typedef struct arr_##name {
//   int size;
//   type *arr;
// } arr_##name;
//
// arr_##name alloc_arr_##name(int len) {
//   arr_##name a = {len, len > 0 ? malloc(sizeof(type) * len) : NULL};
//   return a;
// }
//
//
arr_arr_integer spiralNumbers(int n)
{
	int count=1, x=0, y=n-1;
	arr_arr_integer matrix=alloc_arr_arr_integer(n);
	for(int i=0;i<n;i++)
		matrix.arr[i]=alloc_arr_integer(n);

	while(count<=n*n)
	{
		for(int i=x;i<=y;i++)
			matrix.arr[x].arr[i]=count++;
		for(int i=x+1;i<=y;i++)
			matrix.arr[i].arr[y]=count++;
		for(int i=y-1;i>=x;i--)
			matrix.arr[y].arr[i]=count++;
		for(int i=y-1;i>=x+1;i--)
			matrix.arr[i].arr[x]=count++;
		x++;
		y--;
	}

	return matrix;
}
728x90

'Codesignal' 카테고리의 다른 글

<Codesignal> Add Two Digits  (0) 2020.04.07
<Codesignal> Sudoku  (0) 2020.04.06
<Codesignal> messageFromBinaryCode  (0) 2020.04.06
<Codesignal> File Naming  (0) 2020.04.06
<Codesignal> digitsProduct  (0) 2020.04.06

+ Recent posts