【重点】【BFS】994.腐烂的橘子

2023-12-16 12:02:31

题目

法1:BFS

此方法类似二叉树层次搜索。

class Solution {
    public int orangesRotting(int[][] grid) {
        int[] dx = {-1, 1, 0, 0}; // 方向数组
        int[] dy = {0, 0, -1, 1};
        Queue<int[]> queue = new LinkedList<>();
        int m = grid.length, n = grid[0].length, res = 0, flash = 0;
        int[][] copyGrid = new int[m][n]; // 复制,保证不改变原始输入数组
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                copyGrid[i][j] = grid[i][j];
                if (grid[i][j] == 1) {
                    ++flash;
                } else if (grid[i][j] == 2) {
                    queue.offer(new int[]{i, j});
                }
            }
        }
        
        while (flash > 0 && !queue.isEmpty()) {
            ++res;
            int tmpSize = queue.size();
            for (int i = 0; i < tmpSize; ++i) {
                int[] loc = queue.poll();
                int x = loc[0], y = loc[1];
                for (int k = 0; k < 4; ++k) {
                    int newX = x + dx[k];
                    int newY = y + dy[k];
                    if ((newX >= 0 && newX < m) 
                            && (newY >= 0 && newY < n)
                            && copyGrid[newX][newY] == 1) {
                        copyGrid[newX][newY] = 2;
                        queue.offer(new int[]{newX, newY});
                        --flash;
                    }
                }
            }
        }

        if (flash > 0) {
            return -1;
        } 

        return res;
    }
}

文章来源:https://blog.csdn.net/Allenlzcoder/article/details/135027515
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。