上述过程中,对于每一轮,我们考虑的是与上一轮格子相邻的、未被计算过的格子 x,其高度必然比上一轮的格子高度多 1。反证之:如果格子 x 的高度小于或等于上一轮的格子高度,那么 x 必然会在更早的轮数被计算出来,矛盾。因此 x 的高度必然比上一轮的格子高度高,同时由于题目要求任意相邻的格子高度差至多为 1,因此 x 的高度必然比上一轮格子的高度多 1。
classSolution: defhighestPeak(self, isWater: List[List[int]]) -> List[List[int]]: m, n = len(isWater), len(isWater[0]) ans = [[water - 1for water in row] for row in isWater] q = deque((i, j) for i, row inenumerate(isWater) for j, water inenumerate(row) if water) # 将所有水域入队 while q: i, j = q.popleft() for x, y in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)): if0 <= x < m and0 <= y < n and ans[x][y] == -1: ans[x][y] = ans[i][j] + 1 q.append((x, y)) return ans
publicint[][] HighestPeak(int[][] isWater) { int m = isWater.Length, n = isWater[0].Length; int[][] ans = newint[m][]; for (int i = 0; i < m; ++i) { ans[i] = newint[n]; Array.Fill(ans[i], -1); // -1 表示该格子尚未被访问过 } Queue<Tuple<int, int>> queue = new Queue<Tuple<int, int>>(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (isWater[i][j] == 1) { ans[i][j] = 0; queue.Enqueue(new Tuple<int, int>(i, j)); // 将所有水域入队 } } } while (queue.Count > 0) { Tuple<int, int> p = queue.Dequeue(); foreach (int[] dir in dirs) { int x = p.Item1 + dir[0], y = p.Item2 + dir[1]; if (0 <= x && x < m && 0 <= y && y < n && ans[x][y] == -1) { ans[x][y] = ans[p.Item1][p.Item2] + 1; queue.Enqueue(new Tuple<int, int>(x, y)); } } } return ans; } }
type pair struct{ x, y int } var dirs = []pair{ {-1, 0}, {1, 0}, {0, -1}, {0, 1} }
funchighestPeak(isWater [][]int) [][]int { m, n := len(isWater), len(isWater[0]) ans := make([][]int, m) for i := range ans { ans[i] = make([]int, n) for j := range ans[i] { ans[i][j] = -1// -1 表示该格子尚未被访问过 } } q := []pair{} for i, row := range isWater { for j, water := range row { if water == 1 { // 将所有水域入队 ans[i][j] = 0 q = append(q, pair{i, j}) } } } forlen(q) > 0 { p := q[0] q = q[1:] for _, d := range dirs { if x, y := p.x+d.x, p.y+d.y; 0 <= x && x < m && 0 <= y && y < n && ans[x][y] == -1 { ans[x][y] = ans[p.x][p.y] + 1 q = append(q, pair{x, y}) } } } return ans }