#include <stdio.h>
#include <stdlib.h>
#define not !
#define and &&
#define or ||
#define ri register int
#define rep(inc, frm, to) for (ri inc = frm; inc < (to); ++inc)
#define rep2(inc, frm, to) for (ri inc = frm; inc > (to); --inc)
typedef long long int ll;
#define r() fast_read()
#define MAX_N 1010
int is_digit(const char c) {
return c >= 48 and c <= 57;
}
ll fast_read(void) {
ll n = 0, sign = 1;
char c = getchar();
while (not is_digit(c)) {
if (c == '-') sign = ~0;
c = getchar();
}
while (is_digit(c)) {
n = (n << 1) + (n << 3) + (c ^ 48);
c = getchar();
}
return sign * n;
}
typedef struct Coordinate Coord;
struct Coordinate {
int x, y;
} q[MAX_N * MAX_N];
int front, rear;
void print_board(int** board, const size_t m, const size_t n) {
rep(y, 0, m) rep(x, 0, n) printf("%d%c", *(*(board + y) + x), x == n - 1 ? 10 : 32);
}
void BFS(int** board, const size_t m, const size_t n) {
const int dirs[] = {0, -1, 0, 1, 0};
int steps = 0;
while (front < rear) {
size_t s = rear - front;
while (s--) {
const int x = (q + front)->x, y = (q + front)->y; ++front;
rep(d, 0, 4) {
const int nx = x + *(dirs + d), ny = y + *(dirs + d + 1);
if (not(nx >= 0 and nx < n and ny >= 0 and ny < m and *(*(board + ny) + nx) < 0))
continue;
*(q + rear++) = (Coord) {nx, ny};
*(*(board + ny) + nx) = steps + 1;
}
}
++steps;
}
}
signed main(int argc, char const *argv[]) {
// freopen("test.in", "r", stdin);
int m = r(), n = r(), board[MAX_N][MAX_N];
char s[MAX_N];
rep(y, 0, m) {
scanf("%s", s);
rep(x, 0, n) {
*(*(board + y) + x) = *(s + x) - 49;
if (!*(*(board + y) + x)) *(q + rear++) = (Coord) {x, y};
}
}
int* rows_of_board[m];
rep(y, 0, m)
*(rows_of_board + y) = *(board + y);
BFS(rows_of_board, m, n);
print_board(rows_of_board, m, n);
// fclose(stdin);
return ~~(0 ^ 0);
}
BFS Template 和#173题一样 一行代码都没改
#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
const int N = 1010;
int g[N][N], visited[N][N], m, n;
int main() {
cin >> m >> n;
string line;
for (int i = 0; i < m; ++i) {
cin >> line;
for (int j = 0; j < n; ++j) g[i][j] = line[j] - '0';
}
memset(visited, 0, sizeof visited);
queue<pair<int, int>> q;
for (int y = 0; y < m; ++y)
for (int x = 0; x < n; ++x)
if (g[y][x] == 1) {
q.emplace(x, y);
visited[y][x] = 1;
}
static constexpr int dirs[] { 0, -1, 0, 1, 0};
int steps = 0;
while (not q.empty()) {
size_t sz = q.size();
while (sz--) {
const auto [x, y] = q.front(); q.pop();
g[y][x] = steps;
for (int i = 0; i < 4; ++i) {
int nx = x + dirs[i], ny = y + dirs[i + 1];
if (nx < 0 || ny < 0 || nx == n || ny == m || visited[ny][nx])
continue;
q.emplace(nx, ny);
visited[ny][nx] = 1; // mark as visted
}
}
++steps;
}
for (int y = 0; y < m; ++y) {
for (int x = 0; x < n; ++x) printf("%d ", g[y][x]);
printf("\n");
}
return 0;
}