LeetCode - 01 Matrix

EY·2021년 4월 7일
0

leetcode

목록 보기
4/6

<문제>

<답안>

var updateMatrix = function(matrix) {
    for (let i=0; i<matrix.length; i++) {
        for (let j=0; j<matrix[i].length; j++) {
            matrix[i][j] = BFS(matrix, i, j)
        }
    }
    return matrix
};

function BFS(matrix, y, x) {
    let currentVal;
    let current;
    let q = [{y, x, dist:0}]
    
    while(q.length > 0) {
        current = q.shift();
        
        if (matrix[current.y] === undefined || matrix[current.y][current.x] === undefined) continue
        
        currentVal = matrix[current.y][current.x]
        
        if (currentVal === 0) return current.dist
        
        q.push({y:current.y+1, x:current.x, dist:current.dist+1})
        q.push({y:current.y, x:current.x+1, dist:current.dist+1})
        q.push({y:current.y-1, x:current.x, dist:current.dist+1})
        q.push({y:current.y, x:current.x-1, dist:current.dist+1})
        
    }
}
profile
코딩을 좋아하는 개발자 입니다

0개의 댓글