😎풀이

  1. BFS 기반으로 너비 우선 탐색
  2. 주변 셀 중 현재 셀이 M인 경우 X로 변경하고 즉시 종료
  3. 현재 셀이 E인 경우, 주변 셀을 탐색하며 다음 조건 수행
    3-1. 주변에 지뢰가 존재하지 않는 셀이라면, 주변 셀 BFS Queue에 추가
    3-2. 주변에 지뢰가 존재하는 셀이라면, 주변 지뢰의 수 등록
  4. 완성된 Minesweeper Board 반환
function updateBoard(board: string[][], click: number[]): string[][] {
    const rows = board.length
    const cols = board[0].length
    const visited = new Set<string>()
    visited.add(`${click[0]},${click[1]}`)
    const queue = [click]
    while(queue.length) {
        const [row, col] = queue.shift()
        if(board[row][col] === 'M') {
            board[row][col] = 'X'
            break
        }
        let nearMines = 0
        let neighbors = []
        for(let ny = row - 1; ny <= row + 1; ny++) {
            for(let nx = col - 1; nx <= col + 1; nx++) {
                if(ny < 0 || ny >= rows || nx < 0 || nx >= cols) continue
                if(ny === row && nx === col) continue
                if(board[ny][nx] === 'M') {
                    nearMines++
                    continue
                }
                neighbors.push([ny, nx])
            }
        }
        if(nearMines !== 0) {
            board[row][col] = String(nearMines)
            continue
        }
        board[row][col] = 'B'
        for(const [ny, nx] of neighbors) {
            const curKey = `${ny},${nx}`
            if(visited.has(curKey)) continue
            visited.add(curKey)
            queue.push([ny, nx])
        }
    }
    return board
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글