自己的做法,暴力遍历,没有解出来呜呜
思路:
#include
#include
#include
#include
using namespace std;
int main() {
vector> grid = { {0,1,0,0}, {1, 1, 1, 0}, {0, 1, 0, 0}, {1, 1, 0, 0} };
int i, j;
int rowSum = 0, colSum = 0;
// 计算行周长
for(i = 0; i <= grid.size(); i++){
for (j = 0; j < grid[i].size(); j++) {
if (i == 0) {
if (grid[i][j] == 1) rowSum++;
}
if (i == grid.size()) {
if (grid[i - 1][j] == 1) rowSum++;
}
if (grid[i - 1][j] && grid[i][j]) continue;
else {
rowSum++;
}
}
}
printf("rowSum:%d\n", rowSum);
// 计算列周长
for (i = 0; i < grid.size(); i++) {
for (j = 0; j <= grid[i].size(); j++) {
if (j == 0) {
if (grid[i][j]) colSum++;
}
if (j == grid.size()) {
if (grid[i][j - 1]) colSum++;
}
if (grid[i][j - 1] && grid[i][j]) continue;
else {
colSum++;
}
}
}
printf("colSum:%d\n", colSum);
int sum = rowSum + colSum;
printf("%d\n", sum);
return 0;
}
做出来的报数组下标越界错误。
官方题解:
依次遍历每个格子,针对每个格子,再 依次遍历这个格子的每个边。如果这个边 (不是边界 或 旁边格子是水域) ,那么周长就加上当前边。
核心代码:
const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {1, 0, -1, 0};
i,j;
for(int k = 0; k < 4; k++){
int tx = i + dx[k];
int ty = j + dy[k];
if(tx < 0 || tx >= n || ty < 0 || ty >= m || !grid[tx][ty]){
cnt += 1;
}
}
示例遍历:
i = 0, j = 0, 跳过
i = 0, j = 1, k = 0 (格子的 右边)
tx = 0 + dx[0] = 0 + 0 = 0;
ty = 1 + dy[0] = 1 + 1 =2;
grid[tx][ty] = grid[0][2] 看它右边格子是否有值,无则加 1;
i = 0, j = 1, k = 1 (格子的 下边)
tx = 0 + dx[1] = 0 + 1 = 1;
ty = 1 + dy[1] = 1 + 0 =1;
grid[tx][ty] = grid[1][1] 看它下边格子是否有值,无则加 1;
i = 0, j = 1, k = 2 (格子的 左边)
tx = 0 + dx[2] = 0 + 0 = 0;
ty = 1 + dy[2] = 1 + -1 =0;
grid[tx][ty] = grid[0][0] 看它左边格子是否有值,无则加 1;
i = 0, j = 1, k = 3 (格子的 上边)
tx = 0 + dx[3] = 0 + -1 = -1;
ty = 1 + dy[3] = 1 +0 =1;
tx < 0 说明是上边界,跳过
这里的 dx、dy 数组 的构造: