7084:迷宫问题
题目链接http://noi.openjudge.cn/ch0205/7084/
思路 :BFS+queue,用string 记录走的方向,然后溯源。
这道题真的是花了我很多时间,题目很基础,不难,但是找到自己很多知识盲区。然后自己的收获写在另外一篇文章中,有一些做题注意事项,以及新的知识点链接https://blog.csdn.net/weixin_46028214/article/details/114031981
#include<iostream>
#include<string>
#include<cstring>
#include<queue>
using namespace std;
char a[10][10];
int fx[4][2] = {
{
1,0},{
-1,0} ,{
0,-1},{
0,1} };
typedef struct Node {
Node(string ss, int xx, int yy) :s(ss), x(xx), y(yy) {
}
string s;
int x, y;
}node;
queue<node> q;
bool visited[10][10];
string str;
bool pd(int x, int y) {
//注意
return x >= 0 && x < 5 && y >= 0 && y < 5;
}
void bfs() {
while (!q.empty()) {
node temp = q.front();
q.pop();
if (temp.x == 4 && temp.y == 4) {
str = temp.s;
break;
}
for (int i = 0; i < 4; i++) {
int x = temp.x + fx[i][0], y = temp.y + fx[i][1];
if (pd(x,y)&&!visited[x][y] && a[x][y] == '0') {
visited[x][y] = 1;
q.push(node(temp.s + to_string(i), x, y));
}
}
}
}
int main() {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
cin >> a[i][j];
}
}
q.push(node("", 0, 0));
memset(visited, 0, sizeof(visited));
visited[0][0] = 1;
bfs();
int x = 0, y = 0;
printf("(0, 0)\n");
for (int i = 0; i < str.size(); i++) {
x += fx[str[i]-'0'][0], y += fx[str[i]-'0'][1];//注意
printf("(%d, %d)\n", x, y);
}
return 0;
}