๐Ÿ˜ฎ542 01 Matrix

https://leetcode.com/problems/01-matrix/

่ถ…็บงๅฎนๆ˜“tle๏ผŒ้€š่ฟ‡็š„ๆ–นๆณ•ๆ˜ฏไปŽ0่€Œไธๆ˜ฏ1ๅผ€ๅง‹bfs๏ผŒๅŒๆ—ถไธ่ฆ้‡ๅˆฐไธ€ไธชๅฐฑbfsไธ€ๆฌก๏ผŒๆŠŠๆ‰€ๆœ‰0็š„ไฝ็ฝฎ้ƒฝๅŠ ่ฟ›ๅŽปๅ†bfs๏ผŒbfs็š„่ฟ‡็จ‹ไธญๆ›ดๆ–ฐans

ideaๆ˜ฏๅœจ็ฌฌไธ€่ฝฎๅฐฑๆ‰พๅˆฐๆ‰€ๆœ‰ๅ’Œ0็›ดๆŽฅๆŽฅ่งฆ็š„1๏ผŒๆ›ดๆ–ฐๅฎƒไปฌ็š„่ท็ฆป๏ผˆไนŸๅฐฑๆ˜ฏ1๏ผ‰๏ผŒ็„ถๅŽqueue้‡ŒๆŽฅไธ‹ๆฅๅ‰ฉไธ‹็š„ๅฐฑๆ˜ฏไธ€ๅฑ‚ไธ€ๅฑ‚ๅ’Œ0้—ดๆŽฅๆŽฅ่งฆ็š„1ไบ†

class Solution {
    public int[][] DIR = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
    private class Node {
        int i;
        int j;
        
        public Node(int i, int j) {
            this.i = i;
            this.j = j;
        }
        public String toString() {
            return i + " " + j;
        }
    }
    public int[][] updateMatrix(int[][] mat) {
        int m = mat.length;
        int n = mat[0].length;
        int[][] ans = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (mat[i][j] == 1) {
                    ans[i][j] = Integer.MAX_VALUE;
                }
            }
        }
        Queue<Node> queue = new ArrayDeque<>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (mat[i][j] == 1) {
                    continue;
                }
                queue.offer(new Node(i, j));
            }
        }
        bfs(mat, ans, queue);
        return ans;
    }
    private void bfs(int[][] mat, int[][] ans, Queue<Node> queue) {
        Set<String> visited = new HashSet<>();
        int len = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int s = 0; s < size; s++) {
                Node node = queue.poll();
                // System.out.println(node.toString());
                if (visited.contains(node.toString())) {
                    continue;
                }
                visited.add(node.toString());
                if (mat[node.i][node.j] == 1) {
                    // System.out.println(ans[node.i][node.j]);
                    ans[node.i][node.j] = Math.min(ans[node.i][node.j], len);
                }
                for (int[] dir : DIR) {
                    int x = node.i + dir[0];
                    int y = node.j + dir[1];
                    if (x >= 0 && x < mat.length && y >= 0 && y < mat[0].length) {
                        queue.offer(new Node(x, y));
                    }
                }
            }
            len++;
        }
    }
}

Last updated