烂橘LeetCode 看起来还不错!

问题描述

我正在尝试解决此问题:https://leetcode.com/problems/rotting-oranges/

该链接比我的视觉效果更好地解释了,但是基本上,您必须使每个与“烂”(值2)烂的橙都变烂。

我正在使用BFS进行处理。我首先为所有烂橙子制作一个队列,然后将其传递给我的bfs函数,该函数检查是否可以进行(向上/向下/向左/向右),然后将其添加到队列并将值更改为显示该节点已经被访问过。

我的解决方案没有给我正确的答案,我不确定逻辑上的失误在哪里。

class Solution {
    public int orangesRotting(int[][] grid) {
        
        //get all 2's into a queue
        //iterate over 2 making all oranges rotten
        //iterate grid again --> anything that's not 2,return -1
        //else return count
        Queue<String> q = new LinkedList<>();
        for(int i = 0; i < grid.length; i++) {
            for(int j = 0; j < grid[i].length; j++) {
                if(grid[i][j] == 2) {
                    q.add("" + i + j);
                }
            }
        }

        int count = getMinutes(grid,q);
        
        for(int i = 0; i < grid.length; i++) {
            for(int j = 0; j < grid[i].length; j++) {
                if(grid[i][j] == 1) {
                    return -1;
                }
            }
        }
        return count;
    }
    
    public static int getMinutes(int[][] grid,Queue<String> q) {
        
        Queue<String> rotten = new LinkedList<>();

        int count = 0;
        final int[][] SHIFTS = {
            {1,0},{-1,{0,1},-1}
        };
        
        while(true) {
            while(!q.isEmpty()) {
                String s = q.remove();
                 int i = Integer.parseInt(s.substring(0,s.length() - 1));
                 int j = Integer.parseInt(s.substring(s.length() - 1));
                
                for(int[] points : SHIFTS) {
                    int tempI = i + points[0];
                    int tempJ = j + points[1];
                    if(isValidMove(grid,tempI,tempJ)) {
                        rotten.add("" + tempI + tempJ);
                        grid[tempI][tempJ] =  2; //it's visited
                    }
                }
            }
            if(rotten.isEmpty()) {
                return count;
            }
            count++;
            q = rotten;
        }
    }
    
    public static boolean isValidMove(int[][] grid,int i,int j) {
        if(i < 0 || i >= grid.length || j < 0 || j >= grid[i].length || grid[i][j] != 1) {
            return false;
        }
        return true;
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)