java迷宫问题 华为_迷宫问题, 华为

深度优先遍历搜索。

从(0,0)开始整个矩阵矩阵,只能向上向下,向左向右走,且前方没有障碍物并且没有走过。遍历过程需要记录下来当前点是从哪个点(如果为点(i,j)存储对于id: i*m+j)走过来的。当遍历到(n,m)时,可以得到一条最短路径。然后从(n,m)倒序恢复整条路径。

import java.util.*;

public class Main {

static int[] dx, dy;

static int[][] bfs(int[][] grid, int n, int m) {

//id : x*m + y

int[][] ans = new int[n][m];

Queue q = new LinkedList<>();

q.offer(0);

while(!q.isEmpty()) {

int cur = q.poll();

int x = cur / m, y = cur % m;

//System.out.println(x+","+y);

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

int xx = dx[j] + x, yy = dy[j] + y;

if(xx>= 0 && xx=0 && yy < m && grid[xx][yy] == 0) {

grid[xx][yy] = 2;

q.offer(xx*m+yy);

ans[xx][yy] = cur;

}

}

}

//System.out.println(Arrays.deepToString(ans));

return ans;

}

public static void main(String[] args){

Scanner sc = new Scanner(System.in);

dx = new int[] {0, 1, 0, -1};

dy = new int[] {1, 0, -1, 0};

while(sc.hasNext()){

int n =sc.nextInt(), m = sc.nextInt();

int[][] grid = new int[n][m];

for(int i=0; i < n; i++)

for(int j=0; j < m; j++)

grid[i][j] = sc.nextInt();

int[][] path = bfs(grid, n, m);

List res = new ArrayList<>();

res.add(new int[] {n-1, m-1});

int x = n-1, y = m-1;

while(!(x == 0 && y == 0)) {

int t = path[x][y];

x = t / m; y = t % m;

res.add(new int[] {x, y});

}

for(int i=res.size()-1; i >= 0; i--) {

System.out.println("(" + res.get(i)[0] +"," + res.get(i)[1]+")");

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值