[c언어] 지뢰 찾기
2020. 12. 21. 16:44ㆍComputer Science/C
지뢰는 문자 *로 표시하고 일반 셀은 #으로 표시한다. 입력의 예는 아래와 같다.
#####
#*###
##*##
#*###
###*#
결과는 지뢰가 설치되어 있지 않은 셀 위치에 주변 지뢰의 개수를 출력한다.
위 예제의 결과는 아래와 같다.
#include <stdio.h>
#define X_VALUE 5
#define Y_VALUE 5
void readBombInfo(char grid[][Y_VALUE + 1])
{
int i;
for (i = 0;i < X_VALUE;i++)
scanf("%s", grid[i]);
}
void countBomb(char grid[][Y_VALUE + 1], int numOfBombs[][Y_VALUE])
{
int i, j;
for (i = 0;i < X_VALUE;i++)
for (j = 0;j < Y_VALUE;j++)
if (grid[i][j] == '*') {
if (i - 1 >= 0) {
numOfBombs[i - 1][j]++;
if (j - 1 >= 0)
numOfBombs[i - 1][j - 1]++;
if (j + 1 < Y_VALUE)
numOfBombs[i - 1][j + 1]++;
}
if (i + 1 < X_VALUE) {
numOfBombs[i + 1][j]++;
if (j - 1 >= 0)
numOfBombs[i + 1][j - 1]++;
if (j + 1 < Y_VALUE)
numOfBombs[i + 1][j + 1]++;
}
if (j - 1 >= 0)
numOfBombs[i][j - 1]++;
if (j + 1 < Y_VALUE)
numOfBombs[i][j + 1]++;
}
}
void display_numOfBombs(char grid[][Y_VALUE + 1], int numOfBombs[][Y_VALUE])
{
int i, j;
for (i = 0;i < X_VALUE;i++) {
for (j = 0;j < Y_VALUE; j++)
if (grid[i][j] == '*')
printf("*");
else
printf("%d", numOfBombs[i][j]);
printf("\n");
}
}
int main(void)
{
char grid[X_VALUE][Y_VALUE + 1];
int numOfBombs[X_VALUE][Y_VALUE] = { 0 };
readBombInfo(grid);
countBomb(grid, numOfBombs);
display_numOfBombs(grid, numOfBombs);
}
'Computer Science > C' 카테고리의 다른 글
[c언어] 난수의 합과 가장 큰 수 구하기 (1차원 배열과 포인터) (0) | 2020.12.21 |
---|---|
[c언어] 합집합, 교집합, 차집합 (배열과 함수) (0) | 2020.12.21 |
[c언어] 행렬 곱 (0) | 2020.12.21 |
[c언어] 행렬 합 (0) | 2020.12.21 |
[c언어] 2차원 배열 90도 회전 (0) | 2020.12.21 |