java广度优先遍历之迷宫路程距离计算

package com.sjk;

import org.junit.Test;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class migong {

    private int[][] edges = {
            {0, 1, 1, 1, 0, 1, 1, 0, 0},
            {1, 1, 1, 1, 0, 0, 1, 0, 1},
            {0, 1, 1, 1, 0, 0, 0, 0, 1},
            {0, 0, 1, 0, 1, 0, 1, 1, 1},
            {0, 0, 1, 1, 0, 1, 0, 1, 0},
            {1, 0, 1, 0, 1, 0, 1, 0, 0},
            {0, 1, 1, 1, 0, 1, 0, 1, 0},
            {0, 0, 0, 1, 1, 1, 1, 1, 0},
            {0, 1, 1, 1, 0, 0, 0, 1, 0}
    };

    int[] xStep = {-1, 1, 0,0};
    int[] yStep = {0, 0, -1, 1};
    // 顶点数
    private int number = 9;
    private boolean[][] vister = new boolean[number][number];
    private int[] startIndex = {0, 1};
    // 记录顶点是否被访问
    private boolean[] flag;

    @Test
    public void main() {
        this.BFS();
    }

    void BFS() {
        flag = new boolean[number];
        Queue<int[]> queue = new LinkedList<int[]>();
        queue.add(startIndex);
        vister[startIndex[0]][startIndex[1]] = true;
        int x_step_temp = 0;
        int y_step_temp = 0;
        while (!queue.isEmpty()) {
            int[] node = queue.poll();
            vister[node[0]][node[1]] = true;
            for (int i = 0; i < 4; i++) {
                x_step_temp = node[0] + xStep[i];
                y_step_temp = node[1] + yStep[i];
                if(x_step_temp == -1 || y_step_temp == -1 || x_step_temp >= number || y_step_temp >= number){
                    continue;
                }
                if(!vister[x_step_temp][y_step_temp] && edges[x_step_temp][y_step_temp] != 0){
                    vister[x_step_temp][y_step_temp] = true;
                    edges[x_step_temp][y_step_temp] = edges[node[0]][node[1]] + 1;
                    int[] cur_temp_int = new int[2];
                    cur_temp_int[0] = x_step_temp;
                    cur_temp_int[1] = y_step_temp;
                    queue.add(cur_temp_int);
                }
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值