Java实现迷宫问题

迷宫问题

public class test3 {
    public static void search(int[][] maze, int n, int m){
        Node1[] sq = new Node1[n*m];
        for(int i = 0; i < n*m; i ++){
            sq[i] = new Node1(0,0);
        }
        int[][] mm = new int[n+2][m+2];
        for(int i = 0; i < n+2; i ++){
            mm[i][0] = 1;
            mm[i][m+1] = 1;
        }
        for(int j = 0; j < m+2; j ++){
            mm[0][j] = 1;
            mm[n+1][j] = 1;
        }
        for(int i = 1; i < n+1; i ++){
            for(int j = 1; j < m+1; j ++){
                mm[i][j] = maze[i-1][j-1];
            }
        }
        //四周八个方位的转化
        move[] move = new move[8];
        move[0] = new move(0,1);
        move[1] = new move(1,1);
        move[2] = new move(1,0);
        move[3] = new move(1,-1);
        move[4] = new move(0,-1);
        move[5] = new move(-1,-1);
        move[6] = new move(-1,0);
        move[7] = new move(-1,1);
        int front = 1, rear = 1;
        sq[1].x = 1;
        sq[1].y = 1;
        sq[1].pre = 0;
        mm[1][1] = -1;
        while(front <= rear){
            int x = sq[front].x;
            int y = sq[front].y;
            for(int v = 0; v < 8; v ++) {
                int i = x + move[v].x;
                int j = y + move[v].y;
                if (mm[i][j] == 0) {
                    rear++;
                    sq[rear].x = i;
                    sq[rear].y = j;
                    sq[rear].pre = front;
                    mm[i][j] = -1;
                }
            }
            front ++;
        }
        Output(sq,rear);
    }
    public static void Output(Node1[] node,int rear){
        int i = rear;
        while(i != 0){
            System.out.println("(" +node[i].x +"," + node[i].y +")" );
            i = node[i].pre;
        }
    }
    public static void main(String[] args) {
        int[][] maze = new int[6][8];
        maze= new int[][]{{0,1,1,1,0,1,1,1},{1,0,1,0,1,0,1,0},{0,1,0,0,1,1,1,1},{0,1,1,1,0,0,1,1},{1,0,0,1,1,0,0,0,},{0,1,1,0,0,1,1,0}};
        search(maze,6,8);
     }
}

public class Node1 {
    int x = 0;
    int y = 0;
    int pre = 0;
    public Node1(int x, int y){
        this.x = x;
        this.y = y;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值