从左上角洪泛改了几格
从 (0,0) 出发,把连着的 1 全改成 2。运行下面这段程序:
本节的网格(四行四列,1 是陆地,0 是海):1100 / 1001 / 0010 / 1000。
#include <algorithm>
#include <iostream>
#include <queue>
#include <string>
#include <utility>
#include <vector>
using namespace std;
vector<vector<int>> GRID_MAP = {{1, 1, 0, 0}, {1, 0, 0, 1}, {0, 0, 1, 0}, {1, 0, 0, 0}};
const vector<pair<int, int>> D4 = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
const vector<pair<int, int>> D8 = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
int flood(vector<vector<int>>& g, int si, int sj, int nw) {
int m = g.size(), n = g[0].size();
int old = g[si][sj];
if (old == nw) return 0;
vector<pair<int, int>> st = {{si, sj}};
g[si][sj] = nw;
int k = 1;
while (!st.empty()) {
auto [x, y] = st.back();
st.pop_back();
for (auto [dx, dy] : D4) {
int a = x + dx, b = y + dy;
if (a >= 0 && a < m && b >= 0 && b < n && g[a][b] == old) {
g[a][b] = nw;
st.push_back({a, b});
k++;
}
}
}
return k;
}
int main() {
cout << flood(GRID_MAP, 0, 0, 2) << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论