leetcode 542. 01 매트릭스 (01 매트릭스)

여기에 이미지 설명을 삽입하세요
여기에 이미지 설명을 삽입하세요

행렬에는 0과 1의 값만 있으며, 각 셀에서 가장 가까운 0까지의 거리를 반환합니다.

아이디어:

0 요소에서 그 자체까지의 거리는 0입니다.
1에서 가장 가까운 0까지의 거리를 고려하세요.

BFS.

먼저 요소 1의 거리를 무한대로 업데이트합니다.
0의 위치가 대기열에 로드됩니다.
각각 0부터 시작하여 상하좌우 4방향으로 이동하며 0을 만나면 처리할 필요가 없으며 1을 만나면 현재 거리 + 1이 됩니다.

현재 거리 +1이 다음 위치의 거리보다 작으면
다음 위치의 거리를 현재 거리 +1로 업데이트하고 동시에 다음 위치로부터의 거리를 업데이트하여 로드해야 함을 나타냅니다. 대기열.

    public int[][] updateMatrix(int[][] mat) {
    
    
        int rows = mat.length;
        int cols = mat[0].length;

        Queue<int[]> queue = new LinkedList<>();
        int max = rows * cols;

        //初始化,0处加入queue, 1处设为最大值
        for(int r = 0; r < rows; r++) {
    
    
            for(int c = 0; c < cols; c++) {
    
    
                if(mat[r][c] == 0) queue.offer(new int[]{
    
    r,c});
                else mat[r][c] = max;
            }
        }

        int[] direc = new int[]{
    
    -1,0,1,0,-1};

        while(!queue.isEmpty()) {
    
    
            int[] cur = queue.poll();
            for(int i = 0; i < 4; i++) {
    
    
                int nextR = cur[0] + direc[i];
                int nextC = cur[1] + direc[i+1];
                if(nextR >= 0 && nextR < rows && nextC >= 0 && nextC < cols && mat[cur[0]][cur[1]]+1 < mat[nextR][nextC]){
    
    
                    mat[nextR][nextC] = mat[cur[0]][cur[1]]+1;
                    queue.offer(new int[]{
    
    nextR, nextC});
                }
            }
        }
        return mat;
    }

Guess you like

Origin blog.csdn.net/level_code/article/details/132402351
01