poj 3009 (dfs)

刚开始看到最短路,第一反应是bfs,但是题中说明可以破坏路障,所以需要保存状态,bfs保存状态很困难,所以改用dfs,
1.第一次没注意破坏的障碍应该回溯,所以wa
2.第二次用dfs的时候保存当前状态的时候用了全局变量,所以一直没调出来。

#include <iostream>
#include <cstdio>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <set>
#include <vector>
#include <map>
#include <algorithm>
#include <cmath>
#include <stack>
#include <stdlib.h>
#include <stdio.h>

#define INF 0x3f3f3f3f
#define LINF 0x3f3f3f3f3f3f3f3f
#define ll long long
#define ull unsigned long long
#define uint unsigned int
#define l(x) x<<1
#define r(x) x<<1|1
#define ms(a,b) memset(a,b,sizeof(a))

using namespace std;

struct node {
	int x, y;

	node(){}
	node(int a,int b):x(a),y(b){}
	bool operator==(const node&b) {
		return (x == b.x&&y == b.y);
	}
};

int h, w, mmap[33][33],res;
node beg, en;
int dir[4][2] = {0,-1,0,1,1,0,-1,0};

int run(const node &f, node &r, int d) {
	r = f;
	r.x += dir[d][0];
	r.y += dir[d][1];
	if (mmap[r.x][r.y] == 1) return 0;

	while (1) {
		if (r.x >= h || r.x < 0 ||
			r.y >= w || r.y < 0) return 0;
		if (mmap[r.x][r.y] == 3) {
			return 2;
		}
		if (mmap[r.x][r.y] == 1) {
			r.x -= dir[d][0];
			r.y -= dir[d][1];
			return 1;
		}
		r.x += dir[d][0];
		r.y += dir[d][1];
	}
}

void dfs(node no, int times) {
	if (times == 10)
		return;

	node temp;
	for (int i = 0; i < 4; i++) {
		if (run(no, temp, i) == 1) {
			mmap[temp.x + dir[i][0]][temp.y + dir[i][1]] = 0;
			dfs(temp, times + 1);
			mmap[temp.x + dir[i][0]][temp.y + dir[i][1]] = 1;
		}
		else if (run(no, temp, i) == 2) {
			res = min(res, times+1);
		}
	}
}

int main() {
	while (scanf("%d%d", &w, &h), h) {
		for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
				scanf("%d", &mmap[i][j]);
				if (mmap[i][j] == 2) {
					beg.x = i;
					beg.y = j;
					//uesd[i][j] = 1;
				}
				else if (mmap[i][j] == 3) {
					en.x = i;
					en.y = j;
				}
			}
		}
		res = INF;
		dfs(beg,0);
		if (res == INF)
			printf("-1\n");
		else
			printf("%d\n", res);
	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值