본문 바로가기

Algorithm/Brute Force

(C++) - 백준(BOJ) 4108 : 지뢰찾기

반응형

https://www.acmicpc.net/problem/4108

 

4108번: 지뢰찾기

C개의 문자들이 포함된 R개의 줄을 출력한다. 단, 모든 '.' 대신 인접한 칸에 위치한 지뢰의 수로 변경해 출력한다. '*' 칸은 그대로 출력한다. 문자 사이에 공백이나 줄 사이에 공백 줄이 있어선

www.acmicpc.net

모든 곳을 탐색해 답을 구하는 brute force문제였습니다.

📕 풀이방법

📔 입력 및 초기화

행 r, 열 c, 지뢰상태를 입력받을 이차원 배열 board, 정답을 출력할 변수 ans를 선언 후 매 test case마다 적절히 입력받습니다.

📔 풀이과정

3가지를 수행합니다.1. board정보를 입력받습니다.2. 정답을 구합니다.현재 i행 j열이라면 i - 1행 ~ i+1행까지, j-1열 ~ j+1열까지 범위를 잡아 *개수를 세준뒤 i행 j열의 ans에 저장해줍니다.3. 정답을 출력합니다.

📔 정답출력

ans를 형식에 맞게 출력합니다.


📕 Code

#include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
using namespace std;
int r, c;
char board[101][101], ans[101][101];

void printAns(){
  for(int i = 0; i < r; i++){
    for(int j = 0; j < c; j++){
      cout << ans[i][j];
    }
    cout << '\n';
  }
}

void inputBoard(){
  for(int i = 0; i < r; i++){
    for(int j = 0; j < c; j++){
      cin >> board[i][j];
    }
  }
}

char getMineNum(int start, int end){
  int cnt = 0;
  for(int ri = start - 1; ri <= start + 1; ri++){
    for(int cj = end - 1; cj <= end + 1; cj++){
      if(0 > ri || ri >= r || 0 > cj || cj >= c) continue;
      if(board[ri][cj] =='*') cnt++;
    }
  }
  return cnt + '0';
}

void makeAns(){
  for(int i = 0; i < r; i++){
    for(int j = 0; j < c; j++){
      if(board[i][j] == '*') {
        ans[i][j] = '*';
        continue;
      }
      ans[i][j] = getMineNum(i,j);
    }
  }
}

int main(){
  fastio;
  while(1){
    cin >> r >> c;
    if(!r && !c) break;
    inputBoard();
    makeAns();
    printAns();
  }
}