Swust OJ 004 Maze Problem

该博客讨论了如何在给定的迷宫中寻找从起点到终点的最短路径。输入包含多个测试用例,每个用例表示一个迷宫地图,其中'S'标记起点,'E'标记终点,'-'为空地,'#'为障碍。输出要求打印出每个测试用例的最短路径,若不存在路径则输出-1。
Time limit(ms): 1000
Memory limit(kb): 65535
Submission: 661
Accepted: 280
Accepted
搜索

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

Description

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.
Input

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

Output
1
2
3
4
5
6
7
8
1
5 5
S-###
-----
##---
E#---
---##
Sample Input

1
2
9
/*
 *  题意:求迷宫入口到出口的最短距离
 *  bfs大水题。。
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
#include <stack>
#include <cmath>
#include <queue>
using namespace std;
int dir[4][2] = { {-1,0}, {0,1}, {0,-1}, {1,0} };
char map[101][101];
bool vis[101][101];
int startI, startJ;
int endI, endJ;
int col, row;
struct Node {
	int step;
	int row;
	int col;
};
void bfs() {
	bool flag = true;
	queue<Node>q;
	Node p;
	p.row = startI;
	p.col = startJ;
	p.step = 0;
	for (int i = 0; i < 101; i++)
		for (int j = 0; j < 101; j++)
			vis[i][j] = 0;
	fill(vis, vis + 101 * 101, 0);
	q.push(p);
	vis[p.row][p.col] = 1;
	while (!q.empty()) {
		Node p = q.front();
		q.pop();
		int r = p.row;
		int c = p.col;
		if (r == endI && c == endJ) {
			flag = false;
			cout << p.step << endl;
			break;
		}
		for (int i = 0; i < 4; i++) {
			Node s;
			s.row = r + dir[i][0];
		    s.col = c + dir[i][1];
			if (s.row>=0 && s.col>=0 && s.row<row && s.col<col && !vis[s.row][s.col] && map[s.row][s.col]!='#') {
				vis[s.row][s.col] = 1;
				s.step = p.step + 1;
				q.push(s);
			}
		}
	}
	if (flag) {
		cout << "-1" << endl;
	}
}
int main(){
	int t;

	cin >> t;
	while (t--) {
		cin >> row >> col;
		for (int i = 0; i < row; i++)
			for (int j = 0; j < col; j++) {
				cin >> map[i][j];
				if (map[i][j] == 'S') {
					startI = i;
					startJ = j;
				}
				if (map[i][j] == 'E') {
					endI = i;
					endJ = j;
				}
			}
		bfs();
	}
	return 0;
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值