【HIHOCODER 1478】 水陆距离(BFS)

描述


给定一个N x M的01矩阵,其中1表示陆地,0表示水域。对于每一个位置,求出它距离最近的水域的距离是多少。
矩阵中每个位置与它上下左右相邻的格子距离为1。

输入


第一行包含两个整数,N和M。
以下N行每行M个0或者1,代表地图。
数据保证至少有1块水域。
对于30%的数据,1 <= N, M <= 100
对于100%的数据,1 <= N, M <= 800

输出


输出N行,每行M个空格分隔的整数。每个整数表示该位置距离最近的水域的距离。

样例输入

4 4  
0110  
1111  
1111  
0110

样例输出

0 1 1 0  
1 2 2 1  
1 2 2 1  
0 1 1 0

题解


以水域为起点,使用bfs搜索,一旦一个水域搜到一个陆地,其它水域就不必搜到这个陆地,因为这已经是最短路了

import java.util.*;
import java.io.*;
public class Main {
	static final int N = 810;
	static final int M = (int) 7e5 + 10;
	static final int inf = 0x3f3f3f3f;
	int[][] ans = new int[N][N];
	char[][] a = new char[N][N];
	int[][] book = new int[N][N];
	int n, m;
	class node {
		public int x, y, step;
		node() {
		};
		node(int tx, int ty, int s) {
			x = tx;
			y = ty;
			step = s;
		};
	}

	int nex[][] = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };
	Queue<node> q = new LinkedList<>();

	void bfs() {
		node u = new node(), v = new node();
		while (!q.isEmpty()) {
			u = q.poll();
			if (a[u.x][u.y] == '1')
				ans[u.x][u.y] = Math.min(ans[u.x][u.y], u.step);
			for (int i = 0; i < 4; i++) {
				v.x = u.x + nex[i][0];
				v.y = u.y + nex[i][1];
				if (v.x >= n || v.y >= m || v.x < 0 || v.y < 0)
					continue;
				if (book[v.x][v.y] == 1)
					continue;
				book[v.x][v.y] = 1;
				v.step = u.step + 1;
				q.offer(new node(v.x, v.y, v.step));
			}
		}
	}

	void solve() {
		Scanner sc = new Scanner(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
		n = sc.nextInt();
		m = sc.nextInt();
		for (int i = 0; i < n; i++)
			Arrays.fill(ans[i], inf);
		for (int i = 0; i < n; i++) {
			a[i] = sc.next().toCharArray();
			for (int j = 0; j < m; j++) {
				if (a[i][j] == '0') {
					q.offer(new node(i, j, 0));
					ans[i][j] = 0;
				}
			}
		}
		bfs();
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (j > 0)
					out.print(" ");
				out.print(ans[i][j]);
			}
			out.println();
		}
		out.flush();
	}
	public static void main(String[] args) {
		Main a = new Main();
		a.solve();
	}
}