
😎풀이
- 큐 생성
mat 순회
2-1. 0인 요소의 좌표를 찾아 큐에 입력
2-2. 1인 요소를 Infinity로 설정
- 큐 내의 모든 좌표 탐색
3-1. 상 우 하 좌 방향 탐색
3-2. mat 내의 범위인지 판별
3-3. 다음 요소가 현재 요소에 1을 더한 거리보다 더 멀리있다면 현재 거리 + 1로 갱신
- 갱신된 가장 가까운 0 까지의 거리가 저장된 2차원 배열
mat 반환
function updateMatrix(mat: number[][]): number[][] {
const queue = []
const m = mat.length
const n = mat[0].length
for(let row = 0; row < m; row++) {
for(let col = 0; col < n; col++) {
if(mat[row][col] === 1) {
mat[row][col] = Infinity
continue
}
queue.push([row, col])
}
}
const direct = [[-1, 0], [0, 1], [1, 0], [0, -1]]
while(queue.length) {
const [r, c] = queue.shift()
for(const [y, x] of direct) {
const nr = r + y
const nc = c + x
const isOutBoundary = nr < 0 || nr >= m || nc < 0 || nc >= n
if(isOutBoundary) continue
if(mat[nr][nc] <= mat[r][c] + 1) continue
mat[nr][nc] = mat[r][c] + 1
queue.push([nr, nc])
}
}
return mat
};