代码实现:
int orangesRotting(int **grid, int gridRowSize, int *gridColSizes) {int good = 0, bad = 0, t = 0;for (int i = 0; i < gridRowSize; i++) {for (int j = 0; j < gridColSizes[0]; j++) {if (grid[i][j] == 1) { // 记录好橘子数good++;} else if (grid[i][j] == 2) { // 记录坏橘子数bad++;}}}if (good == 0) {return 0;}if (bad == 0) {return -1;}int new_good = good;while (new_good) { // 直到好橘子数为零t++; // 时间加1for (int i = 0; i < gridRowSize; i++) {for (int j = 0; j < gridColSizes[0]; j++)if (grid[i][j] == 2) { // 检查坏橘子四周if (i && grid[i - 1][j] == 1) {grid[i - 1][j] = 3; new_good--;}if (j && grid[i][j - 1] == 1) {grid[i][j - 1] = 3; new_good--;}if (i != gridRowSize - 1 && grid[i + 1][j] == 1) {grid[i + 1][j] = 3; new_good--;}if (j != gridColSizes[0] - 1 && grid[i][j + 1] == 1) {grid[i][j + 1] = 3;new_good--;}}}for (int i = 0; i < gridRowSize; i++) {for (int j = 0; j < gridColSizes[0]; j++) {if (grid[i][j] == 3) { // 重新变为2,方便下一次检查grid[i][j] = 2;}}}if (new_good == good) { // 没有新的橘子变坏return -1;}good = new_good; // 还剩的好橘子}return t; }