四邻域方向技巧

2022-01-10  本文已影响0人  book_02

1. 一维数组写法

//...
const int dirs[5] = { -1, 0, 1, 0, -1 };

while (!pq.empty()) {
    auto e = pq.top(); pq.pop();
    for (int k = 0; k < 4; ++k) {
        int nx = e[0] + dirs[k];
        int ny = e[1] + dirs[k + 1];

        if (inArea(nx, ny)) {
            // ...
        }
    }
}
//...

3. 二维数组写法 (更直观的写法)

// ...
const int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

while (!pq.empty()) {
    auto e = pq.top(); pq.pop();
    for (int k = 0; k < 4; ++k) {
        int nx = e[0] + dirs[k][0];
        int ny = e[1] + dirs[k][1];

        if (inArea(nx, ny)) {
            // ...
        }
    }
}
//...
上一篇 下一篇

猜你喜欢

热点阅读