java bfs_java实现广度搜索(bfs)最短路径

这篇博客介绍了一种使用Java实现广度优先搜索(BFS)来寻找二维矩阵中最短路径的方法。通过创建队列存储节点,并用4个方向进行遍历,更新地图状态,直到找到目标位置并输出最短步数。
摘要由CSDN通过智能技术生成

import java.util.LinkedList;

/**

* 广度搜索,查找最小距离

*/

public class BFS {

static int map[][] = new int[4][4];

public static void main(String[] args) {

for (int i = 0; i < 4; i++) {

for (int j = 0; j < 4; j++) {

map[i][j] = 0;

}

}

new BFS().bfs(3, 3);

}

public void bfs(int end_r, int end_c) {

int next[][] = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };// 4个方向

LinkedList q = new LinkedList();// 队列存储

Node start = new Node(0, 0, 0);

q.offer(start);

while (!q.isEmpty()) {

Node temp = q.poll();

if (temp.row == end_r && temp.cloumm == end_r) {

System.out.println(temp.round);

break;

}

for (int i = 0; i < 4; i++) {

int r = temp.row + next[i][0];

int c = temp.cloumm + next[i][1];

if (r > 3 || c > 3 || r < 0 || c < 0 || map[r][c] == 1) {

continue;

}

map[r][c] = 1;

q.offer(new Node(r, c, temp.round + 1));

}

}

}

class Node {

int row;

int cloumm;

int round;

public Node(int row, int cloumm, int round) {

super();

this.row = row;

this.cloumm = cloumm;

this.round = round;

}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值