BFS广度搜索(迷宫问题)

来源:互联网 发布:javascript onclick 编辑:程序博客网 时间:2024/05/22 09:04


/*  0, 1, 0, 0, 0,0, 1, 0, 1, 0,0, 0, 0, 0, 0,0, 1, 1, 1, 0,0, 0, 0, 1, 0,*/public class BFS {private static int[][] array = { { 0, 1, 0, 0, 0 }, { 0, 1, 0, 1, 0 }, { 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 0 },{ 0, 0, 0, 1, 0 } };private static List<Node> list = new ArrayList<>();static BFS b = new BFS();public static void main(String[] args) {BFS.Node Vs = b.new Node(0, 0);// 入口BFS.Node Vd = b.new Node(4, 4);// 出口b.bfs(Vs, Vd);}boolean bfs(Node Vs, Node Vd) {Node Vn;// 当前点Node Vw;// 下一点int i;boolean[][] visit = new boolean[5][5];int[][] dir = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };list.add(Vs);visit[Vs.x][Vs.y] = true;while (!list.isEmpty()) {Vn = list.get(0);list.remove(0);System.out.println(Vn.x+"-"+Vn.y);for (i = 0; i < 4; i++) {Vw = b.new Node(Vn.x + dir[i][0], Vn.y + dir[i][1]);if (Vw.x == Vd.x && Vw.y == Vd.y) {return true;}if (isValid(Vw) && array[Vw.x][Vw.y] != 1 && !visit[Vw.x][Vw.y]) {list.add(Vw);visit[Vw.x][Vw.y] = true;}}}return false;}// 点的位置是否合法boolean isValid(Node node) {if (node.x < 0 || node.y < 0 || node.x >= array[0].length || node.y >= array.length) {return false;}return true;}class Node {public int x;public int y;public Node(int x, int y) {this.x = x;this.y = y;}}}




参考 http://blog.csdn.net/raphealguo/article/details/7523411

0 0