
😎풀이
board 전체 순회
1-1. 함선의 일부분(X)이 탐색될 경우, 함선을 카운트하고 해당 함선의 모든 부분을 탐색해서 방문 기록 작성
1-2. 이후 방문되지 않은 함선의 일부분이 추가로 발견될 때마다, 함선을 카운트하고 동일 작업 반복
- 발견된 함선의 수 반환
function countBattleships(board: string[][]): number {
let battleships = 0
const rows = board.length
const cols = board[0].length
const visited = new Set<string>()
function dfs(y: number, x: number) {
if(y < 0 || y >= rows || x < 0 || x >= cols) return
const curKey = `${y},${x}`
if(visited.has(curKey)) return
visited.add(curKey)
if(board[y][x] !== 'X') return
dfs(y + 1, x)
dfs(y - 1, x)
dfs(y, x + 1)
dfs(y, x - 1)
}
for(let row = 0; row < rows; row++) {
for(let col = 0; col < cols; col++) {
if(board[row][col] !== 'X') continue
if(visited.has(`${row},${col}`)) continue
battleships++
dfs(row, col)
}
}
return battleships
};