您的位置:首页 > 其它

<OJ_Sicily>无路可逃?

2016-05-16 17:50 281 查看
Description
唐僧被妖怪关在迷宫中。孙悟空好不容易找到一张迷宫地图,并通过一个魔法门来到来到迷宫某个位置。假设迷宫是一个n*m的矩阵,它有两种地形,1表示平地,0表示沼泽,孙悟空只能停留在平地上。孙悟空目前的位置在坐标(sx,sy)处,他可以向上下左右四个方向移动。
请你帮助孙悟空计算一下,迷宫中是否存在一条路从他所在位置(sx,sy)到达唐僧所在位置(tx,ty)?
Input
输入第一行为一个整数t(0<t<=10),表示测试用例个数。
每个测试样例的第1行是2个正整数n (1≤n≤100),m (1≤n≤100),表示迷宫是n*m的矩阵。接下来的n行输入迷宫,每行有m个数字(0或者1),数字之间用一个空格间隔。
接下来的1行是4个整数sx,sy,tx,ty,1≤sx,tx≤n,1≤sy,ty≤m,表示孙悟空所在位置为第sx行第sy列,唐僧所在位置为第tx行第tx列。迷宫左上角编号是(1,1),右下角编号是(n, m)。
数据保证(sx,sy)格和(tx,ty)必定为平地。
Output
每个样例单独输出一行:1表示路径存在,0表示路径不存在。
解题思路:同样使用广度搜索算法实现
#include <iostream>
#include <string.h>
#include <stack>
using namespace std;
int mapArr[105][105];
int moveStep[4][2]= {{-1,0},{1,0},{0,-1},{0,1}};
int n,m;
struct points{
int x, y;
};
bool canMove(int x, int y){
if (x >=1 && x <= n && y >=1 && y <= m && mapArr[x][y] == 1) {
return true;
}
return false;
}
int main(int argc, const char * argv[]) {
// insert code here...
int caseNum;
cin >> caseNum;
while (caseNum--) {

cin >> n >> m;
memset(mapArr, 0, sizeof(mapArr));  // 对地图进行初始化
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> mapArr[i][j];
}
}
int sx,sy,tx,ty;
cin >> sx >> sy >> tx >> ty;
bool result = false;
points tmp_point;
tmp_point.x = sx;
tmp_point.y = sy;
stack<points> st;
st.push(tmp_point);
st.push(tmp_point);
while (!st.empty()) {   // 进行广度搜索
points tmp = st.top();
st.pop();
if (tmp.x == tx && tmp.y == ty) {
result = true;
break;
}
points tmp_new ;
for (int i = 0; i < 4; i++) {
tmp_new.x = tmp.x + moveStep[i][0];
tmp_new.y = tmp.y + moveStep[i][1];
if (canMove(tmp_new.x, tmp_new.y)) {
st.push(tmp_new);
mapArr[tmp_new.x][tmp_new.y] = 0;
}
}
}
if (result) cout << "1" << endl;
else cout << "0" << endl;

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: