Medium

In the popular Minesweeper game you have a board with some mines and those cells that don't contain a mine have a number in it that indicates the total number of mines in the neighboring cells. Starting off with some arrangement of mines we want to create a Minesweeper game setup.

Example

For

matrix = [[true, false, false],

                   [false, true, false],

                   [false, false, false]]

the output should be

minesweeper(matrix) = [[1, 2, 1],

                                                [2, 1, 1],

                                                [1, 1, 1]]

Check out the image below for better understanding:

Input/Output

  • [execution time limit] 0.5 seconds (c)

  • [input] array.array.boolean matrix

    A non-empty rectangular matrix consisting of boolean values - true if the corresponding cell contains a mine, false otherwise.

    Guaranteed constraints:
    2 ≤ matrix.length ≤ 100,
    2 ≤ matrix[0].length ≤ 100.

  • [output] array.array.integer

    • Rectangular matrix of the same size as matrix each cell of which contains an integer equal to the number of mines in the neighboring cells. Two cells are called neighboring if they share at least one corner.

[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 minesweeper(arr_arr_boolean matrix)
{
	arr_arr_integer mine=alloc_arr_arr_integer(matrix.size);
	for(int i=0;i<mine.size;i++)
		mine.arr[i]=alloc_arr_integer(matrix.arr[0].size);

	for(int i=0;i<mine.size;i++)
		for(int j=0;j<mine.arr[0].size;j++)
		{
			mine.arr[i].arr[j]=0;

			for(int k=-1;k<=1;k++)
				for(int l=-1;l<=1;l++)
					if(!(i+k<0 || j+l<0 || (k==0&&l==0) || i+k>=mine.size || j+l>=mine.arr[0].size))
						mine.arr[i].arr[j]+=matrix.arr[i+k].arr[j+l]==true;
		}

	return mine;
}
728x90

'Codesignal' 카테고리의 다른 글

<Codesignal> evenDigitsOnly  (0) 2020.04.05
<Codesignal> Array Replace  (0) 2020.04.05
<Codesignal> Box Blur  (0) 2020.04.05
<Codesignal> avoidObstacles  (0) 2020.04.05
<Codesignal> isIPv4Address  (0) 2020.04.05

+ Recent posts