已知一个N*N的迷宫,允许上,左,下,右,左上,左下,右上,右下,八个方位任意探索,且迷宫中有障碍物(用1表示障碍物不能通过,0表示没有障碍物能通过),请找出迷宫中任意两点V1,V2之间的路径。
输入格式:
第一行是一个正整数N代表迷宫大小。
第二行是两个非负整数,中间以空格分开代表起始点V1的坐标。
第三行是两个非负整数,中间以空格分开代表终点V2的坐标。
接下来的N列N行由1和0构成的数组代表迷宫的地图。
输出格式:
输出可行路径的坐标,坐标之间用"->"链接,不同路径之间用换行隔开。
若没有路径请输出“没有路径”。
输入样例1:
3
0 0
2 2
0 1 1
1 1 0
1 1 0
输出样例1:
没有路径
输入样例2:
3
0 0
2 2
0 0 1
1 1 0
1 1 0
输出样例2:
(0,0)->(0,1)->(1,2)->(2,2)
输出样例3:
7
0 0
6 6
0 1 1 1 1 1 1
1 0 1 1 0 1 1
0 1 1 1 0 1 1
0 1 0 1 0 1 1
1 0 1 0 1 1 1
1 1 1 1 0 1 1
0 0 1 1 0 0 0
输出样例3:
(0,0)->(1,1)->(2,0)->(3,0)->(4,1)->(3,2)->(4,3)->(5,4)->(6,4)->(6,5)->(6,6)
(0,0)->(1,1)->(2,0)->(3,0)->(4,1)->(3,2)->(4,3)->(5,4)->(6,5)->(6,6)
解题思路:深度优先遍历和回溯,是上次发布的解决迷宫路径问题的升级版,但核心依旧不变。
解决迷宫路径问题:http://t.csdn.cn/nqcs8
本题代码如下:
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int xy=0;
Maze s=new Maze(n);
int x=sc.nextInt();
int y=sc.nextInt();
int xx=sc.nextInt();
int yy=sc.nextInt();
s.over(xx, yy);
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
xy=sc.nextInt();
if(xy==1)
s.b[i][j]=true;
}
s.b[x][y]=true;//标记此点已经走过
s.dfs(x, y, 0);
s.print1();
}
}
class Maze
{
boolean b[][];//标记是否走过
int c[][];//储存路径
int fx[];
int fy[];//遍历顺序
int N,I,J,flag;
Maze(int n)
{
this.N=n-1;
b=new boolean[n][n];
c=new int [n*n][3];
int xx[]= {0,-1,0,1,-1,-1,1,1};
int yy[]= {-1,0,1,0,-1,1,-1,1};//上,左,下,右,左上,左下,右上,右下
fx=xx;
fy=yy;
}
public void over(int i,int j)
{
this.I=i;
this.J=j;
}
public void dfs(int x,int y,int k)
{
c[k][1]=x;
c[k][2]=y;
//先存入此点
if(x==I&&y==J)
{
print(k);
}
int tx=0,ty=0;
for(int i=0;i<8;i++)
{
tx=x+fx[i];
ty=y+fy[i];//上左下右遍历
if(tx>=0&&tx<=N&&ty>=0&&ty<=N&&b[tx][ty]!=true)
{
b[tx][ty]=true;//标记走过
dfs(tx,ty,k+1);
b[tx][ty]=false;//回溯到前一个状态
}
}
}
public void print(int k)
{
for(int i=0;i<k;i++)
System.out.print("("+c[i][1]+","+c[i][2]+")"+"->");
System.out.println("("+c[k][1]+","+c[k][2]+")");
flag++;
}
public void print1()
{ if(flag==0)
System.out.print("没有路径");
}
}
(创作这道题的原因,是因为朋友问我能否走出他设的迷宫,刚好又是刚学会迷宫路径,但我又不想局限于就四个方向探索, 所以就创作了这个八个方向纵情探索任意两点路径的升级版。)