腐爛的橘子

flag

軟件學院大三黨,每天一道算法題,第25天

題目介紹

在給定的網格中,每個單元格可以有以下三個值之一:

值 0 代表空單元格;
值 1 代表新鮮橘子;
值 2 代表腐爛的橘子。
每分鐘,任何與腐爛的橘子(在 4 個正方向上)相鄰的新鮮橘子都會腐爛。

返回直到單元格中沒有新鮮橘子爲止所必須經過的最小分鐘數。如果不可能,返回 -1。
1
2
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/rotting-oranges

思路

①採用hashmap將矩陣和對應的值保存起來,其中矩陣的index降二維爲一維,i*columns+j
②採用minute計數,while循環一次minute+1,循環條件爲map中還存在值爲1的鍵值對(代表新鮮水果還存在)
③循環中遍歷map,如果發現值爲2的鍵值對,將其上下左右的值都變成-1(一個暫時的值,不能直接變成2)。一次循環結束後,將所有的-1變成2
④如果出現水果永遠不腐爛的情況,利用minutes判斷
在這裏插入圖片描述

關鍵代碼

    public static int orangesRotting(int[][] grid){
        int rows = grid.length;//行數
        int columns = grid[0].length;//列數
        int minutes=0;//時間
        Map<Integer,Integer> map=new HashMap();
        for(int i=0;i<rows;i++) {//將矩陣錄入哈希表
            for (int j = 0; j < columns; j++) {
                if(grid[i][j]==1){
                    map.put(i*columns+j,1);
                }
                if(grid[i][j]==2){
                    map.put(i*columns+j,2);
                }
                if(grid[i][j]==0){
                    map.put(i*columns+j,0);
                }

            }
        }
        while (map.containsValue(1)){
            for(int i=0;i<columns*rows;i++){
                if(map.get(i)==2){
                    if(i-columns>=0&&map.get(i-columns)==1){//上方橘子新鮮
                        map.put(i-columns,-1);
                    }
                    if(i+columns<columns*rows&&map.get(i+columns)==1){//下方橘子新鮮
                        map.put(i+columns,-1);
                    }
                    if(i-1>=0 && i%columns!=0 && map.get(i-1)==1){//左方橘子新鮮
                        map.put(i-1,-1);
                    }
                    if(i+1<columns*rows && i%columns!=columns-1 && map.get(i+1)==1){//右方橘子新鮮
                        map.put(i+1,-1);
                    }

                }
            }
            minutes++;
            if(minutes>=columns*rows)
                return -1;
            for(int i=0;i<columns*rows;i++){
                if(map.get(i)==-1){
                    map.put(i,2);
                }

            }
        }
        return minutes;
    }

待優化

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章