刷刷笔试题~~[迷宫问题!!]

1.迷宫问题 定义一个二维数组:

int maze[5][5] = {

	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,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

输入描述

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

输出描述

左上角到右下角的最短路径,格式如样例所示。

输入例子
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
输出例子
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

解析:

这里用的递归来解决

首先用check,,把迷宫过一遍,确定哪些地方不能走,不能走的把map[i][j]=1

在check中返回-1

之后再找path,如果是可以走得路,就在path里面返回坐标,如果不是右下角的出口,就继续走

import java.util.*;
public class Main {
	public static void main(String[] args){
		Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
            int n=sc.nextInt();
		int m=sc.nextInt();
		int[][] map=new int[n][m];
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				map[i][j]=sc.nextInt();
			}
		}
		check(map,0,0);
		System.out.println(path(map,0,0));
        }
		
	}
	public static String path(int[][] map,int x,int y){
		if(x==map.length-1&&y==map[0].length-1)
			return "("+x+","+y+")";
		if(x<map.length&&y<map[0].length&&map[x][y]==0){
			return "(" + x + "," + y + ")" + "\n" + path(map, x + 1, y) + path(map, x, y + 1);
		}
		return "";
	}
	public static int check(int[][] map,int x,int y){
		if(x==map.length-1&&y==map[0].length-1)
			return 1;
		if(x<map.length&&y<map[0].length&&map[x][y]==0){
			if(check(map,x+1,y)==-1&&check(map,x,y+1)==-1){
				map[x][y]=1;
				return -1;
			}
			return 1;
		}return -1;
	}
}

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/nanaMasuda/article/details/52701866
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞