POJ - 3984 迷宫问题

POJ - 3984 链接
bfs最短路的迷宫问题,加上保存路径
const int ax[4] = {1, -1, 0, 0};
const int ay[4] = {0, 0, 1, -1};
const int dir[4] = {0, 1, 2, 3};
这三个分别代表x方向,y方向,路径移动方向对应的数组下标
例如x = 1, y = 2。移动方向是2,则x = x + ax[2], y = y + ay[2], 走到x = 1, y = 3上去了。

// #include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int ax[4] = {1, -1, 0, 0};
const int ay[4] = {0, 0, 1, -1};
const int dir[4] = {0, 1, 2, 3};
int maze[10][10];
struct point{
    int x, y;
    string str;
    point(int a, int b, string c) : x(a), y(b), str(c) {}
};
bool judge(int x, int y) {
    if(x >= 0 && x < 5 && y >= 0 && y < 5 && !maze[x][y])
        return true;
    return false;
}
void bfs() {
    queue<point> q;
    q.push(point(0, 0, ""));
    maze[0][0] = 1;
    while(!q.empty()) {
        point temp = q.front();
        q.pop();
        if(temp.x == 4 && temp.y == 4) {
            int x = 0, y = 0, n = temp.str.size();
            for(int i = 0; i < n; i++) {
                printf("(%d, %d)\n", x, y);
                int d = temp.str[i] - '0';
                x += ax[d];
                y += ay[d];
            }
            printf("(%d, %d)\n", x, y);
            break;
        }
        for(int i = 0; i < 4; i++) {
            int tempx = temp.x + ax[i];
            int tempy = temp.y + ay[i];
            if(judge(tempx, tempy)) {
                maze[tempx][tempy] = 1;
                q.push(point(tempx, tempy, temp.str + (char)('0' + dir[i])));
            }
        }
    }
}
int main() {
    for(int i = 0; i < 5; i++)
        for(int j = 0; j < 5; j++)
            cin >> maze[i][j];
    bfs();
    return 0;
}

这道题有一个非常玄学的dfs不回溯代码,好像就是搜索方向设置的正好符合所有的测试

//Powered by CK
#include<iostream>
#include<cstring>
const int ax[4]={0,0,-1,1};
const int ay[4]={1,-1,0,0};
int maze[5][5],flag;
struct point {
	int x,y;
}ans[50];
using namespace std;
bool judge(int x,int y) {
	if(x>=0&&x<5&&y>=0&&y<5&&!maze[x][y])
		return true;
	return false;
}
void dfs(int x,int y,int pos) {
	if(flag)
		return ;
	if(x==4&&y==4) {
		for(int i=0;i<pos;i++)
			cout<<"("<<ans[i].x<<", "<<ans[i].y<<")"<<endl;
		flag=1;
		return ;
	}
	for(int i=0;i<4;i++) {
		if(judge(x+ax[i],y+ay[i])) {
			maze[x+ax[i]][y+ay[i]]=1;
			ans[pos].x=x+ax[i];
			ans[pos].y=y+ay[i];
			dfs(x+ax[i],y+ay[i],pos+1);
			maze[x+ax[i]][y+ay[i]]=0;
		}
	}
}
int main()
{
	for(int i=0;i<5;i++)
		for(int j=0;j<5;j++)
			cin>>maze[i][j];
	flag=0;
	maze[0][0]=1;
	ans[0].x=0,
	ans[0].y=0;
	dfs(0,0,1);
	return 0;
}
posted @ 2020-01-11 12:51  lifehappy  阅读(158)  评论(0编辑  收藏  举报