LeetCode.540 01 Matrix(距离0最近的距离)

1.题目

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.

2.输入输出样例子

Example 1:

Input:
[[0,0,0],
 [0,1,0],
 [0,0,0]]

Output:
[[0,0,0],
 [0,1,0],
 [0,0,0]]

Example 2:

Input:
[[0,0,0],
 [0,1,0],
 [1,1,1]]

Output:
[[0,0,0],
 [0,1,0],
 [1,2,1]]

Note:

  • The number of elements of the given matrix will not exceed 10,000.
  • There are at least one 0 in the given matrix.
  • The cells are adjacent in only four directions: up, down, left and right.

2.解法

  • 题解:给定的二维矩阵(仅包含0和1),输出各点到0最近的距离(两个坐标点之间的距离单位1)。
class Solution {
    
    // 定义四个点的方向
    int [] deltaX=new int[]{0,0,1,-1};
    int [] deltaY=new int[]{1,-1,0,0};
    
    public int[][] updateMatrix(int[][] matrix) {
        // 思路:非常典型的DFS问题,当一个点不是0时,需要搜索四周使当前距离最小,同理,采用DFS对四周继续遍历
        int m=matrix.length;
        int n=matrix[0].length;
        for(int i=0;i=0&&nextX=0&&nextY=0&&nextX=0&&nextY

你可能感兴趣的:(Java基础学习,LeetCode算法编程,数据结构与算法分析)