1. 程式人生 > >542. 01 Matrix

542. 01 Matrix

pre region style cells out clas tip sem 使用

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.
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.

矩陣的bfs, 考察:

1.哪些是先入隊的? 外圍? 還是遍歷所有符合條件的? 此處改成Integer.Max_Value,

2.入隊之後, 鄰居元素怎麽改讓其入隊. 怎麽跳過不符合題意的元素, visited[] 是否使用

3一般用在改矩陣的題中 tips, 可以該元素e.g. 將‘o‘ 改成‘$‘(見130. Surrounded Regions)

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[][] dirs = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
        while (!queue.isEmpty()) {
            int[] cur = queue.poll();
            for (int[] cell : dirs) {
                int r = cur[0] + cell[0];
                int c = cur[1] + cell[1];
            
                if (r < 0 || r >= m || c < 0 || c >= n || matrix[r][c] <= matrix[cur[0]][cur[1]] + 1) {
                    continue;
                }
                matrix[r][c] = matrix[cur[0]][cur[1]] + 1;
                queue.offer(new int[]{r,c});
            }
        }
        return matrix;
    }

矩陣, 常將元素構造類使用: queue.offer(new int[]{r,c}) 此處可以構造類

542. 01 Matrix