본문 바로가기
Programmers/Lv.0

[프로그래머스][Js] Lv.0 - 안전지대

by pin9___9 2023. 3. 14.
728x90

문제💭


 

나의 풀이👨‍💻

function solution(board) {
    let result = 0
    for(let i = 0 ; i < board.length ; i ++) {
        for(let j = 0 ; j < board[i].length ; j ++) {
            if(board[i][j] === 1) {
                if(i !== 0 && board[i-1][j] !== 1) {
                    board[i-1][j] = 2    
                }
                if(i !== board.length-1 && board[i+1][j] !== 1) {
                    board[i+1][j] = 2
                }
                if(j !== 0 && board[i][j-1] !== 1) {
                    board[i][j-1] = 2
                }
                if(j !== board[i].length-1 && board[i][j+1] !== 1) {
                    board[i][j+1] = 2
                }
                if(i !== 0 && j !== 0 && board[i-1][j-1] !== 1) {
                    board[i-1][j-1] = 2
                }
                if(i !== 0 && j !== board[i].length-1 && board[i-1][j+1] !== 1) {
                    board[i-1][j+1] = 2
                }
                if(i !== board.length-1 && j !== 0 && board[i+1][j-1] !== 1) {
                    board[i+1][j-1] = 2
                }
                if(i !== board.length-1 && j !== board[i].length-1 && board[i+1][j+1] !== 1) {
                    board[i+1][j+1] = 2
                }
            }
        }
    }
    board.forEach(a => a.forEach(b => b === 0 ? result++ : null))
    return result
}

 


다른 사람의 풀이👨‍🏫

1. foreach

function solution(board) {

    let outside = [[-1,0], [-1,-1], [-1,1], [0,-1],[0,1],[1,0], [1,-1], [1,1]];
    let safezone = 0;

    board.forEach((row, y, self) => row.forEach((it, x) => {
        if (it === 1) return false;
        return outside.some(([oy, ox]) => !!self[oy + y]?.[ox + x])
               ? false : safezone++;
    }));

    return safezone;
}

2. 

function solution(b) {
    const directions = [[0,0],[0,1],[0,-1],[1,1],[1,0],[1,-1],[-1,-1],[-1,0],[-1,1]]
    let bombSet = new Set();

    for(let i = 0; i < b.length; i++) {
        for(let j = 0; j < b[i].length; j++) {
            if(b[i][j] == 1) {
                directions.forEach(el => {
                    let [nextX, nextY] = el;
                    [nextX, nextY] = [i+nextX, j+nextY];
                    if(nextX >= 0 && nextX < b.length && nextY >= 0 && nextY < b[i].length) {
                        bombSet.add(nextX+' '+nextY);
                    }
                })
            }
        }
    }
    return b.length * b[0].length - bombSet.size;
}

 


Reference

  • 프로그래머스
 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

728x90

댓글