
😎풀이
grid
를 2중 반복으로 순회한다.
- 순회 중
island
를 만난다면 깊이우선탐색(dfs
)을 진행한다.
2-1. 탐색 도중 이미 탐색한 island(T)
를 만날 경우 중지
2-2. 탐색 도중 바다를 만날 경우 중지
2-3. 동 서 남 북 4방향 중 가능한 모든 방향을 순회하며 연결된 island
를 임시 문자 T
로 설정(재방문 방지)
island
의 수를 증가시킨다.
- 총 탐색된
island
의 수를 반환한다.
function numIslands(grid: string[][]): number {
let result = 0
const m = grid.length
const n = grid[0].length
function dfs(row: number, col: number) {
const current = grid[row][col]
if(current === 'T') return
if(current === '0') return
grid[row][col] = 'T'
if(row + 1 < m) dfs(row + 1, col)
if(row - 1 >= 0) dfs(row - 1, col)
if(col + 1 < n) dfs(row, col + 1)
if(col - 1 >= 0) dfs(row, col - 1)
}
for(let row = 0; row < m; row++) {
for(let col = 0; col < n; col++) {
if(grid[row][col] !== '1') continue
dfs(row, col)
result++
}
}
return result
};