Description
给定一个图\(grid[x][y]\),求实体周长。
Constraints
- \(1 \le x, y \le 100\)
- \(0 \le grid[x][y] \le 1\)
Solution
完了,这可是 真·easy 难度啊,我一时没想法。
扫一遍,然后枚举四边,边隔壁有实体的不算入答案,否则\(+1\)。
顺便摆弄下毫无意义的代码,想找个人骂我。
Code
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int ans = 0;
auto n = grid.size();
auto m = grid[0].size();
auto zip = n * m << 2;
auto unzip = [=](auto z) {
auto xy = z >> 2;
return tuple(xy / m, xy % m, z & 3);
};
constexpr int dx[] {0, !0, ~0, 0};
constexpr int dy[] {!0, 0, 0, ~0};
// zip移除for(x) for(y) for(d)三层循环嵌套
for(auto z = 0ll; z < zip; ++z) {
auto [x, y, d] = unzip(z);
if(!grid[x][y]) continue;
auto nx = x + dx[d];
auto ny = y + dy[d];
ans += (nx < 0 || nx >= n)
|| (ny < 0 || ny >= m)
|| !grid[nx][ny];
}
return ans;
}
};