1 public class Solution 2 { 3 int row = 0; 4 int column = 0; 5 int FreshOrangeCount = 0; 6 int RottenOrangeCount = 0; 7 int Minute = 0; 8 Queue<int[]> Q = new Queue<int[]>(); 9 int[,] TagGrid; 10 public void BFS(int[][] grid) 11 { 12 var rottinglist = new List<int[]>(); 13 14 while(Q.Count>0) 15 { 16 while (Q.Count > 0) 17 { 18 var orange = Q.Dequeue(); 19 20 int i = orange[0]; 21 int j = orange[1]; 22 23 int i_new = -1; 24 int j_new = -1; 25 26 //合法范围:up,down,left,right 27 //未访问的:TagGrid[newi,newj]==0 28 //新鲜的(grid[i][j]==1) 29 i_new = i - 1; 30 j_new = j; 31 32 //up:i-1>=0 33 if (i_new >= 0 && TagGrid[i_new, j_new] == 0 && grid[i_new][j_new] == 1) 34 { 35 FreshOrangeCount--; 36 RottenOrangeCount++; 37 TagGrid[i_new, j_new] = 1;//visited 38 grid[i_new][j_new] = 2;//go bad 39 rottinglist.Add(new int[] { i_new, j_new }); 40 } 41 42 //down:i+1<=row-1 43 i_new = i + 1; 44 j_new = j; 45 if (i_new <= row - 1 && TagGrid[i_new, j_new] == 0 && grid[i_new][j_new] == 1) 46 { 47 FreshOrangeCount--; 48 RottenOrangeCount++; 49 TagGrid[i_new, j_new] = 1;//visited 50 grid[i_new][j_new] = 2;//go bad 51 rottinglist.Add(new int[] { i_new, j_new }); 52 } 53 54 //left:j-1>=0 55 i_new = i; 56 j_new = j - 1; 57 if (j_new >= 0 && TagGrid[i_new, j_new] == 0 && grid[i_new][j_new] == 1) 58 { 59 FreshOrangeCount--; 60 RottenOrangeCount++; 61 TagGrid[i_new, j_new] = 1;//visited 62 grid[i_new][j_new] = 2;//go bad 63 rottinglist.Add(new int[] { i_new, j_new }); 64 } 65 66 //right:j+1<=column-1 67 i_new = i; 68 j_new = j + 1; 69 if (j_new <= column - 1 && TagGrid[i_new, j_new] == 0 && grid[i_new][j_new] == 1) 70 { 71 FreshOrangeCount--; 72 RottenOrangeCount++; 73 TagGrid[i_new, j_new] = 1;//visited 74 grid[i_new][j_new] = 2;//go bad 75 rottinglist.Add(new int[] { i_new, j_new }); 76 } 77 78 } 79 if (rottinglist.Any()) 80 { 81 Minute++; 82 } 83 foreach (var l in rottinglist) 84 { 85 Q.Enqueue(l); 86 } 87 rottinglist.Clear(); 88 } 89 } 90 91 public int OrangesRotting(int[][] grid) 92 { 93 row = grid.Length; 94 column = grid[0].Length; 95 TagGrid = new int[row, column]; 96 97 for (var i = 0; i < row; i++) 98 { 99 for (var j = 0; j < column; j++) 100 { 101 TagGrid[i, j] = 0;//unvisited 102 if (grid[i][j] == 1) 103 { 104 FreshOrangeCount++; 105 } 106 if (grid[i][j] == 2) 107 { 108 RottenOrangeCount++; 109 Q.Enqueue(new int[] { i, j }); 110 } 111 } 112 } 113 114 BFS(grid); 115 116 if (FreshOrangeCount != 0) 117 { 118 return -1; 119 } 120 else 121 { 122 return Minute; 123 } 124 } 125 }