多点bfs

该博客介绍了如何解决RPG游戏中角色寻找最近传送点的问题,利用曼哈顿距离计算从每个网格到最近传送点的距离。通过给出的样例输入和输出,说明了算法的应用和预期效果,同时作者指出代码存在一些问题,可能需要调整优化。
摘要由CSDN通过智能技术生成

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;
        }
    }
}

参考:https://blog.csdn.net/Soul_97/article/details/80427667

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值