Implement a function that assigns correct numbers in a field of Minesweeper, which is represented as a 2 dimensional array.
Example: The size of the field is 3x4, and there are bombs at the positions [0, 0] (row index = 0, column index = 0) and [0, 1] (row index = 0, column index = 1).
Then, the resulting field should be:
- [[-1, -1, 1, 0],
- [2, 2, 1, 0],
- [0, 0, 0, 0]]
Your function should return the resulting 2D array after taking the following three arguments:
- bombs: A list of bomb locations. Given as an array of arrays. Example: [[0, 0], [0, 1]] ([row index = 0, column index = 0], [row index = 0, column index = 1]. Assume that there are no duplicates.
- num_rows: The number of rows in the resulting field.
- num_columns: The number of columns in the resulting field.
In the resulting field:
- -1 represents that there is a bomb in that location.
- 1, 2, 3... etc. represents that there are 1, 2, 3... etc. bombs in the surrounding cells (including diagonally adjacent cells).
- 0 represents that there are no bombs in the surrounding cells.
풀이
지뢰찾기 문제라고 생각하면 편할 거 같다.
bomb에 해당하는 index에 지뢰가 있고(-1), 지뢰 근처에 있는 index들은 +1씩 더해주면 된다(상하좌우 대각선도 포함)
처음에 조건문으로 분기처리를 하다보니 너무 많아져서 고생했다...;
강사의 solution은 상하좌우 대각선을 포함해 9개의 셀을 검토하는데
1. 여기에 조건문으로 행과 열의 범위 안에 들어오게끔
2. 9개 셀을 돌 때 -1 아닌 곳(지뢰가 있지 않은 곳)
에 1을 더해주는 방식으로 해결함
package com.company;
public class Main {
public static void main(String[] args) {
// NOTE: The following input values will be used for testing your solution.
int[][] bombs1 = {{0, 2}, {2, 0}};
// mineSweeper(bombs1, 3, 3);
// [[0, 1, -1],
// [1, 2, 1],
// [-1, 1, 0]]
int[][] bombs2 = {{0, 0}, {0, 1}, {1, 2}};
mineSweeper(bombs2, 3, 4);
// [[-1, -1, 2, 1],
// [2, 3, -1, 1],
// [0, 1, 1, 1]]
int[][] bombs3 = {{1, 1}, {1, 2}, {2, 2}, {4, 3}};
// mineSweeper(bombs3, 5, 5);
// [[1, 2, 2, 1, 0],
// [1, -1, -1, 2, 0],
// [1, 3, -1, 2, 0],
// [0, 1, 2, 2, 1],
// [0, 0, 1, -1, 1]]
}
// Implement your solution below.
public static int[][] mineSweeper(int[][] bombs, int numRows, int numCols) {
int[][] field = new int[numRows][numCols];
for (int i = 0; i < bombs.length; i++) {
int[] array = bombs[i];
int rowIndex = array[0];
int colIndex = array[1];
field[rowIndex][colIndex] = -1;
for (int j = rowIndex - 1; j < rowIndex + 2; j++) {
for (int k = colIndex - 1; k < colIndex + 2; k++) {
if (j >= 0 && j < numRows &&
k >= 0 && k < numCols &&
field[j][k] != -1)
field[j][k] += 1;
}
}
}
return field;
}
}
'Algorithms > 11 Coding Interview (CS Dojo)' 카테고리의 다른 글
Rotating a 2D Array by 90 Degrees (Java) (0) | 2018.03.15 |
---|---|
Find Where to Expand in Minesweeper (Java) (0) | 2018.03.14 |
One Away Strings (Java) (0) | 2018.03.13 |
Non-Repeating Character (Java) (0) | 2018.02.13 |
Is One Array a Rotation of Another? (Java) (0) | 2018.02.13 |