[Algorithm/Java] 백준 4396번 - 지뢰 찾기
https://www.acmicpc.net/problem/4396
🔍 문제 풀이
문제 도식화
배운 점
new String(result[i])
: char[] -> String로 변환- result의 각 행을 한 줄씩 출력한다.
- 한 줄로 간단하게 출력할 수 있어 편리하다.
// 결과 출력
for (int i = 0; i < n; i++) {
System.out.println(new String(result[i]));
}
for문을 쓴 것과 의미는 같다.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(result[i][j]);
}
System.out.println();
}
💻 전체 코드
import java.io.*;
public class Main {
static char[][] board;
static char[][] player;
static char[][] result;
static int n;
static boolean isGameOver = false;
static int[] dx = {-1, -1, -1, 0, 0, 1, 1, 1};
static int[] dy = {-1, 0, 1, -1, 1, -1, 0, 1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
board = new char[n][n];
player = new char[n][n];
result = new char[n][n];
// 지뢰 위치 입력
for (int i = 0; i < n; i++) {
String s = br.readLine();
for (int j = 0; j < n; j++) {
board[i][j] = s.charAt(j);
}
}
// 플레이어 클릭 위치 입력
for (int i = 0; i < n; i++) {
String s = br.readLine();
for (int j = 0; j < n; j++) {
player[i][j] = s.charAt(j);
}
}
// 게임 진행
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// 클릭한 칸
if (player[i][j] == 'x') {
// 지뢰 클릭
if (board[i][j] == '*') {
isGameOver = true;
}
// 지뢰 없는 칸 클릭
else {
result[i][j] = countMines(i, j);
}
}
// 클릭하지 않은 칸
else{
result[i][j] = '.';
}
}
}
// 게임 오버 시 모든 지뢰 표시
if (isGameOver) gameOver();
// 결과 출력
for (int i = 0; i < n; i++) {
System.out.println(new String(result[i]));
}
}
// 게임오버 -> 모든 지뢰 표시
static void gameOver() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == '*') {
result[i][j] = '*';
}
}
}
}
// 주변 지뢰 수 계산
static char countMines(int x, int y) {
int cnt = 0;
for (int d = 0; d < 8; d++) {
int nx = x + dx[d];
int ny = y + dy[d];
if (nx >= 0 && nx < n && ny >= 0 && ny < n) {
if (board[nx][ny] == '*') cnt++;
}
}
return (char)(cnt + '0');
}
}
댓글남기기