leetcode.542 01矩陣

給定一個由 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

注意:

  1. 給定矩陣的元素個數不超過 10000。
  2. 給定矩陣中至少有一個元素是 0。
  3. 矩陣中的元素只在四個方向上相鄰: 上、下、左、右。

思路:BFS 的思路,將矩陣位置爲 0 的下標壓進隊列,並將不爲 0 的元素置爲 Integer 的最大值。然後進行處理,逐漸將隊列中的元素出隊處理,看看這個出隊的元素的上下左右方位,是否爲 Integer 最大值,注意要下標越界的判斷。

代碼:

class Solution {
    public int[][] updateMatrix(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        Queue<int[]> queue = new LinkedList<>();
        for(int i = 0;i < m;++i){
            for(int j = 0;j < n;++j){
                if(matrix[i][j] == 0){
                    queue.offer(new int[]{i,j});
                }else{
                    matrix[i][j] = Integer.MAX_VALUE;
                }
            }
        }

        int[] dir = {{1,0},{-1,0},{0,1},{0,-1}};
        while(!queue.isEmpty()){
            int[] unit = queue.poll();
            for(int[] pos : dir){
                int x = unit[0] + pos[0];
                int y = unit[1] + pos[1];
                if(x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] <= matrix[unit[0]][unit[1]]+1){
                    continue;
                }
                queue.offer(new int[]{x,y});
                matrix[x][y] = matrix[unit[0]][unit[1]] + 1;
            }
        }
        return matrix;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章