java_迷宫BFS

迷宫算法BFS

import java.util.LinkedList;
import java.util.Scanner;

//迷宫BFS广度算法
//使用队列

public class maze_1 {
    static int[][] maze;
    static int x, y;//地图的大小
    static int[] addx={-1,1,0,0};//x向量增加量
    static int[] addy={0,0,-1,1};//y向量增加量
    //(-1,0)、(1,0)、(0,-1)、(0,1)想左,向右,向下,向上移动

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("输入地图的大小");
        x = in.nextInt();
        y = in.nextInt();
        maze = new int[x][y];
        System.out.println("输入地图");
        for (int i = 0; i < x; i++)
            for (int j = 0; j < y; j++)
                maze[i][j] = in.nextInt();
                //System.out.println(i+" "+ j+" "+maze[i][j]);
        System.out.println("输入入口,输入出口");
        int in_x = in.nextInt();
        int in_y = in.nextInt();
        int out_x = in.nextInt();
        int out_y = in.nextInt();
        System.out.println(BFS_1(in_x, in_y, out_x, out_y));
    }

    static int BFS_1(int x_1, int y_1, int out_x, int out_y) {
        LinkedList list = new LinkedList();
        Point point = new Point();
        point.setX(x_1);
        point.setY(y_1);
        point.setDis(0);
        list.add(point);
        maze[point.getX()][point.getY()]=1;
        while (!list.isEmpty()) {
            Point point_1 = list.getFirst();//取出第一个数
            System.out.println("("+point_1.getX()+","+point_1.getY()+")");
            list.removeFirst();//删除第一个数
            if(point_1.getX()==out_x&&point_1.getY()==out_y)
                return point_1.getDis();
            for(int i=0;i<4;i++ )
            {
                if(point_1.getX()+addx[i]=0 && point_1.getY()+addy[i]=0 && maze[point_1.getX()+addx[i]][point_1.getY()+addy[i]]==0)
                    {
                        Point point_2=new Point();
                        point_2.setX(point_1.getX()+addx[i]);
                        point_2.setY(point_1.getY()+addy[i]);
                        point_2.setDis(point_1.getDis()+1);
                        maze[point_2.getX()][point_2.getY()]=1;//加入队列
                        list.add(point_2);
                    }
            }
        }
     return 0;
    }
}
class Point//节点
{
    private int x;//地图的x坐标
    private int y;//地图的有坐标
    private int dis;//在地图中需要的位置步数

    public int getDis() {
        return dis;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public void setDis(int dis) {
        this.dis = dis;
    }

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }
}

//测试代码
1 0 1 0 1 1 1 1 1
1 0 0 1 0 0 1 0 1
1 0 0 1 1 0 0 0 1
1 0 1 0 1 0 0 1 1
1 0 0 0 0 1 0 0 1
1 1 0 1 0 1 0 0 1
1 0 0 1 0 1 0 0 1
1 1 0 1 0 0 0 0 1
1 1 1 1 1 1 1 1 1

你可能感兴趣的:(算法,DFS/BFS)