BFS——刀耕火种

题目:刀耕火种

主要思想与走迷宫相差不大,就是嗅探四周,若可行就入队,直到队空结束

要求多长时间实际上就是求最远的点离原点有多远

所求点结构,step为离起始点距离

public class Node{
        int x;
        int y;
        int step;

        public Node(){}

        public Node(int x,int y,int step){
            this.x = x;
            this.y = y;
            this.step = step;
        }
    }

具体执行代码

public int BFS(char[][] MAT,int N,int row,int col){

        //新建一个图判断走过的路
        boolean[][] map = new boolean[N][N];
        //初始化 可以燃烧为T否则为F
        for (int i = 0; i < map.length; i++) {
            for (int j = 0; j < map.length; j++) {
                if (MAT[i][j] == 'G') {
                    map[i][j] = true;
                }else {
                    map[i][j] = false;
                }
            }
        }

        Queue<Node> nodes = new LinkedList<>();

        nodes.add(new Node(row,col,0));

        while(!nodes.isEmpty()){
            Node tempNode = nodes.poll();
            int x = tempNode.x;
            int y = tempNode.y;
            int step = tempNode.step;

            //已走
            map[x][y] = false;

            //嗅探四周
            if (x+1 < N && map[x+1][y] == true ) {
                nodes.add(new Node(x+1,y,step+1));
            }

            if (x-1 >= 0 && map[x-1][y] == true) {
                nodes.add(new Node(x-1,y,step+1));
            }

            if (y+1 < N && map[x][y+1] == true) {
                nodes.add(new Node(x,y+1,step+1));
            }

            if (y-1 >= 0 && map[x][y-1] == true) {
                nodes.add(new Node(x,y-1,step+1));
            }

            if (nodes.isEmpty()) {
                return tempNode.step;
            }
        }

        return -1;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值