You are given two integers m
and n
representing a 0-indexed m x n
grid. You are also given two 2D integer arrays guards
and walls
where guards[i] = [rowi, coli]
and walls[j] = [rowj, colj]
represent the positions of the ith
guard and jth
wall respectively.
A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it.
Return the number of unoccupied cells that are not guarded.
Example 1:

Input: m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]] Output: 7 Explanation: The guarded and unguarded cells are shown in red and green respectively in the above diagram. There are a total of 7 unguarded cells, so we return 7.
Example 2:

Input: m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]] Output: 4 Explanation: The unguarded cells are shown in green in the above diagram. There are a total of 4 unguarded cells, so we return 4.
Constraints:
1 <= m, n <= 105
2 <= m * n <= 105
1 <= guards.length, walls.length <= 5 * 104
2 <= guards.length + walls.length <= m * n
guards[i].length == walls[j].length == 2
0 <= rowi, rowj < m
0 <= coli, colj < n
- All the positions in
guards
andwalls
are unique.
Solution: Simulation
Enumerate each cell, for each guard, shoot rays to 4 directions, mark cells on the way to 1 and stop when hit a guard or a wall.
Time complexity: O(mn)
Space complexity: O(mn)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// Author: Huahua class Solution { public: int countUnguarded(int m, int n, vector<vector<int>>& guards, vector<vector<int>>& walls) { vector<vector<int>> s(m, vector<int>(n)); for (const auto& g : guards) s[g[0]][g[1]] = 2; for (const auto& w : walls) s[w[0]][w[1]] = 3; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { if (s[i][j] != 2) continue; for (int y = i - 1; y >= 0; s[y--][j] = 1) if (s[y][j] >= 2) break; for (int y = i + 1; y < m; s[y++][j] = 1) if (s[y][j] >= 2) break; for (int x = j - 1; x >= 0; s[i][x--] = 1) if (s[i][x] >= 2) break; for (int x = j + 1; x < n; s[i][x++] = 1) if (s[i][x] >= 2) break; } int ans = 0; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) ans += !s[i][j]; return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment