2018: 跑图
描述
题目描述:
跑图是RPG游戏中很烦躁的事情。玩家需要跑到距离他最近的传送点的位置。现在给你一张N \times MN×M的方格图,每个方格中数值00表示为平地,数值11表示为传送点,你的任务是输出一张N \times MN×M的矩阵,Matrix_{xy}Matrix
xy
表示从(x,y)(x,y)到距离它最近的传送点的距离。 这里的距离是曼哈顿距离,(x_1,y_1) \rightarrow(x_2,y_2)(x
1
,y
1
)→(x
2
,y
2
) 的距离为|x_1-x_2|+|y_1-y_2|∣x
1
−x
2
∣+∣y
1
−y
2
∣。
输入:
第一行,有两个数n,mn,m。接下来nn行,每行mm个数。
数据保证至少有一个传送点。
1 \leq n \leq 5001≤n≤500,1 \leq m \leq 5001≤m≤500
输出:
nn行,每行mm个数,表示某个点到离它最近的传送点的距离。
样例输入
2 3
0 0 0
1 0 1
样例输出
1 2 1
0 1 0
我这里代码有点问题哎,,,,
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class test6{
static int inf = 99999999;
static int dir[][] = new int[][]{{-1,0},{1,0},{0,-1},{0,1}}; //java定义二位数组
static int m;
static int n;
public static int vis[][];
static Queue<Node> queue = new LinkedList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
m = sc.nextInt();
n = sc.nextInt();
int[][] graph = new int[m][n];
int[][] g = new int[m][n];
vis =new int[m][n];//标记哪些点已经被访问
for(int i = 0;i<m;i++){
for(int j = 0;j<n;j++){
graph[i][j] =sc.nextInt();
if(graph[i][j]!=0){
vis[i][j] = inf;
queue.add(new Node(i,j,0));
}
}
}
bfs();
for(int i = 0;i<m;i++){
for(int j =0;j<n;j++){
if(vis[i][j] !=inf){
System.out.print(vis[i][j]+" ");
}else {
System.out.print(0);
}
}
System.out.println();
}
}
static void bfs(){
while (!queue.isEmpty()){
Node node = queue.poll();
for(int i =0;i<4;i++){
int dx = node.x+dir[i][0];
int dy = node.y+dir[i][1];
if(dx<0 || dy<0 || dx>n-1 || dy>m-1 || vis[dx][dy]!=0) continue;
vis[dx][dy] = node.depth+1;
int dep = node.depth+1;
queue.add(new Node(dx,dy,dep));
}
}
}
static class Node{
int x;
int y;
int depth;
public Node(int x, int y, int depth) {
this.x = x;
this.y = y;
this.depth = depth;
}
}
}