力扣542.01矩阵【中等】

看题解之前,只想到了从一开始的广搜,每日一遍自己真菜,使用广搜+队列解决问题,不过并不是从1开始搜索,而是从所有的0开始,因为从1开始一次广搜只能找到一个点的最短路径,而从0开始,碰到路径比当前路径长的都可以被优化。

给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。

两个相邻元素间的距离为 1 。

示例 1:
输入:

0 0 0
0 1 0
0 0 0
输出:

0 0 0
0 1 0
0 0 0
示例 2:
输入:

0 0 0
0 1 0
1 1 1
输出:

0 0 0
0 1 0
1 2 1
注意:

给定矩阵的元素个数不超过 10000。
给定矩阵中至少有一个元素是 0。
矩阵中的元素只在四个方向上相邻: 上、下、左、右。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/01-matrix

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class test542 {
    
    

    public static void main(String[] args) {
    
    
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int[][] s = new int[3][3];
        for (int i = 0; i < 3;i++){
    
    
            try {
    
    
                String[] in = (br.readLine()).split(" ");
                for (int j = 0;j < in.length;j++){
    
    
                    s[i][j] = Integer.parseInt(in[j]);
                }
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
        System.out.println(Arrays.deepToString(updateMatrix(s)));
    }

    public static int[][] updateMatrix(int[][] matrix){
    
    

        int row = matrix.length, col = matrix[0].length;
        int[][] vector = new int[][]{
    
    {
    
    0, 1}, {
    
    0, -1}, {
    
    1, 0}, {
    
    -1, 0}};

        Queue<int[]> queue = new LinkedList<>();

        for (int i = 0;i < row;i++){
    
    
            for (int j = 0; j < col;j++){
    
    
                if (matrix[i][j] == 0)
                {
    
    
                    //多源广度搜索
                    queue.add(new int[] {
    
    i, j});
                }else{
    
    
                    //将路径长度变为不可达。
                    matrix[i][j] = row + col;
                }
            }
        }

        //访问队列中的节点,直至队列为空。
        while (!queue.isEmpty()){
    
    
            int[] s = queue.poll();

            //访问数组上下左右的邻居
            for (int[] ints : vector) {
    
    
                int x = ints[0] + s[0], y = ints[1] + s[1];

                //判断数组是否越界,并将不是最短路径的节点优化为最短,
                //优化后的节点加入队列,以便优化未被优化的邻居。
                if (x >= 0 && x < row && y >= 0 && y < col
                && matrix[x][y] > matrix[s[0]][s[1]] + 1){
    
    
                    matrix[x][y] = matrix[s[0]][s[1]] + 1;
                    queue.add(new int[] {
    
    x,y});
                }
            }
        }

        return matrix;
    }

猜你喜欢

转载自blog.csdn.net/luluxiu_1999/article/details/109076642