SWUST OJ4:迷宫问题

题目描述

给定一个迷宫,找到从开始到目标的最短路径。

输入

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.

输出

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

样例输入

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

样例输出

9

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<malloc.h>
#define INF 0x3f3f3f3f
#define MAX(x,y) (x>y?x:y)
#define MIN(x,y) (x>y?y:x)
#define M 100
int dir[][2] = { {1,0},{0,-1},{0,1},{-1,0} };
char a[M][M];
int vis[M][M];
int xa, ya,xb,yb;
int m, k;
int flag = 1;
struct node
{
	int x;
	int y;
	int step;
}q[M*M];
void bfs(int xb, int yb,int xa,int ya)
{
	int head = 1, tail = 1;
	q[tail].x = xb;
	q[tail].y = yb;
	q[tail].step = 0;
	vis[xb][yb] = 1;
	tail++;
	while (head < tail)
	{
		int x = q[head].x;
		int y = q[head].y;
		int step = q[head].step;
		if (x == xa && y == ya)
		{
			flag = 0;
			printf("%d\n", step);
			break;
		}
		for (int i = 0; i < 4; i++)
		{
			int nx = x + dir[i][0];
			int ny = y + dir[i][1];
			if (nx >= 0 && nx < m && ny >= 0 && ny < k && a[nx][ny] == '-' && vis[nx][ny] == 0)
			{
				vis[nx][ny] = 1;
				q[tail].x = nx;
				q[tail].y = ny;
				q[tail].step = step + 1;
				tail++;
			}
		}
		head++;
	}
	if (flag == 1)
	{
		printf("-1\n");
	}
}
int main()
{
	int n;
	scanf("%d", &n);
	while (n--)
	{
		flag = 1;
		memset(vis, 0, sizeof(vis));
		scanf("%d%d", &m, &k);
		for (int i = 0; i < m; i++)
		{
			scanf("%s", a[i]);
		}
		for (int i = 0; i < m; i++)
		{
			for (int j = 0; j < k; j++)
			{
				if (a[i][j] == 'S')
				{
					xb = i;
					yb = j;
				}
				if (a[i][j] == 'E')
				{
					xa = i;
					ya = j;
					a[i][j] = '-';
				}
			}
		}
		bfs(xb, yb, xa, ya);
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值