当前位置:网站首页>Breadth first search rotten orange

Breadth first search rotten orange

2022-07-06 10:38:00 GUTSZ

Breadth first search rotten orange

problem :
 Insert picture description here

Code :

class pair{
    
    int x;
    int y;
    public pair(int x,int y){
    
        this.x=x;
        this.y=y;
    }
}

class Solution {
    
    public int orangesRotting(int[][] grid) {
    
        if (grid.length == 0)
            return 0;
        int row = grid.length;
        int col = grid[0].length;
        Queue<pair> q = new LinkedList<>();
        // Find the bad fruit , The team 
        for (int i = 0; i < row; i++) {
    
            for (int j = 0; j < col; j++) {
    
                if (grid[i][j] == 2)
                    q.offer(new pair(i, j));
            }
        }
        int[][] nextp = {
    {
    1, 0}, {
    -1, 0}, {
    0, 1}, {
    0, -1}};
        int step = 0;
        while (!q.isEmpty()) {
    
            int size = q.size();
            boolean flag = false;
            while (size-- != 0) {
    
                pair cur = q.poll();
                // Search for a new location 
                for (int i = 0; i < 4; i++) {
    
                    int nx = cur.x + nextp[i][0];
                    int ny = cur.y + nextp[i][1];
                    if (nx >= row || nx < 0 || ny >= col || ny < 0)
                        continue;
                    if (grid[nx][ny] == 1) {
    
                        flag = true;
                        grid[nx][ny] = 2;
                        q.offer(new pair(nx, ny));
                    }
                }
            }
            if (flag)
                step++;
        }
        for (int i = 0; i < row; i++) {
    
            for (int j = 0; j < col; j++) {
    
                if (grid[i][j] == 1)
                    return -1;
            }
        }
        return step;
    }
}

Running results :
 Insert picture description here

原网站

版权声明
本文为[GUTSZ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131705333437.html