YTU OJ-1085: Maze Problem


1085: Maze Problem

Time Limit: 1 Sec   Memory Limit: 128 MB
Submit: 23   Solved: 5
[ Submit][ Status][ Web Board]

Description

Given a maze, find a shortest path from start to goal.

Input

Input consists serveral test cases.

First line of the input contains number of test case T.

For each test case the first line contains two integers N , M ( 1 <= N, M <= 100 ).

Each of the following N lines contain M characters. Each character means a cell of the map.

Here is the definition for chracter.

 

Constraint:

  • For a character in the map:
    • 'S' : start cell
    • 'E' : goal cell
    • '-' : empty cell
    • '#' : obstacle cell
  • no two start cell exists.
  • no two goal cell exists.

Output

For each test case print one line containing shortest path. If there exists no path from start to goal, print -1.

Sample Input

1
5 5
S-###
-----
##---
E#---
---##

Sample Output

9
import java.util.*;
public class Maze_Problem {
	static int[][] map=new int[101][101];
	static int[][] vis=new int[101][101];
	static int[][] dis=new int[101][101];
	static int[] qu=new int[10001];
	static int[] dx= {-1,0,1,0};
	static int[] dy= {0,1,0,-1};
	static int x1,y1,x2,y2;
	static int m,n;
	public static int bfs(int x,int y) {
		int u,nx,ny;
		int front=0,rear=0;
		u=x*m+y;
		vis[x][y]=1;
		dis[x][y]=0;
		qu[rear++]=u;
		while(front<rear) {
			u=qu[front++];
			x=u/m;
			y=u%m;
			for(int i=0;i<4;i++) {
				nx=x+dx[i];ny=y+dy[i];
				if(nx>=0&&nx<m&&ny>=0&&ny<n&&vis[nx][ny]==0&&map[nx][ny]==1) {
					int v=0;
					v=nx*m+ny;
					qu[rear++]=v;
					vis[nx][ny]=1;
					dis[nx][ny]=dis[x][y]+1;
					if(nx==x2&&ny==y2)
						return dis[nx][ny];
				}
			}
		}
		return -1;
	}
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		int t=in.nextInt();
		while(t>0) {
			String s="";
			char[][] c=new char[101][101];
			m=in.nextInt();n=in.nextInt();
			s=in.nextLine();
			for(int i=0;i<m;i++)
				for(int j=0;j<n;j++) {
					map[i][j]=0;
					vis[i][j]=0;
					dis[i][j]=0;
				}
			for(int i=0;i<m;i++) {
				s=in.nextLine();
				for(int j=0;j<n;j++) {
					c[i][j]=s.charAt(j);
					switch(c[i][j]) {
						case 'S':map[i][j]=1;x1=i;y1=j;break;
						case 'E':map[i][j]=1;x2=i;y2=j;break;
						case '-':map[i][j]=1;break;
						case '#':map[i][j]=0;break;
					}
				}
			}
			System.out.println(bfs(x1,y1));
			t--;
		}
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值