문제
내가 작성한 정답
class Solution {
public int solution(int[][] board) {
int answer = 0, len = board.length;
boolean[][] boom = new boolean[len][len];
for(int i=0; i<len; i++){
for(int j=0; j<len; j++){
if(board[i][j]==1){
for(int k = -1; k<2; k++){
for(int l= -1;l<2;l++){
if(i+k<0 || j+l<0 || i+k>len-1 || j+l>len-1) continue;
else boom[i+k][j+l]=true;
}
}
}
}
}
for(boolean[] bb:boom){
for(boolean b: bb){
if(!b) answer++;
}
}
return answer;
}
}다른 사람들의 정답
class Solution {
public int solution(int[][] board) {
int answer = 0;
int length = board.length; //길이
int[][] temp = new int[length+2][length+2];
// 길이를 2 늘린 액자용 배열 생성 -> 이러면 단순한 조건식으로 안전영역 구할 수 있음
// 액자에 board 이식.
for(int i=1; i<length+1; i++){
for(int j=1; j<length+1;j++){
temp[i][j]=board[i-1][j-1];
}
}
//위험지대 찾기
for(int i=1; i<length+1; i++){
for(int j=1; j<length+1;j++){
if(temp[i][j]==1){
for(int a = i-1; a<=i+1; a++){
for(int b =j-1; b<=j+1; b++){
if(temp[a][b]!=1) temp[a][b]=2;
}
}
}
}
}
// 안전지대 카운트
for(int i=1; i<length+1; i++){
for(int j=1; j<length+1;j++){
if(temp[i][j]==0) answer++;
System.out.print(temp[i][j]);
}
System.out.println("");
}
return answer;
}
}
import java.util.Arrays;
import java.util.stream.IntStream;
class Solution {
@FunctionalInterface
interface BiConsumer<T> {
void apply(Integer t1, Integer t2);
}
public int solution(int[][] board) {
int answer;
int[] move = {-1,0,1};
int[][] chkBoard = new int[board.length][board.length];
BiConsumer<Integer> drawChk = (x, y) ->{
Arrays.stream(move)
.filter((i)-> 0<= x+i && x+i < board.length)
.forEach(i->Arrays.stream(move)
.filter(j-> 0 <= j+y && j+y < board.length)
.forEach((j)->chkBoard[x+i][y+j] = 1));
};
IntStream.range(0, board.length).forEach(i -> IntStream.range(0, board.length).filter(j->board[i][j] == 1).forEach(j->drawChk.apply(i,j)));
answer = (int)Arrays.stream(chkBoard).mapToLong(i -> Arrays.stream(i).filter(j -> j == 0).count()).sum();
System.out.println();
return answer;
}
}Share article