HDU 1072

#include 
#include 
#include 
#include 
#include 
#include
using namespace std;
const int MAX = 9;
int go[4][2] = { 1,0,-1,0,0,1,0,-1 };
int map[MAX][MAX], step[MAX][MAX], time[MAX][MAX];
int n, m, sx, sy, dx, dy, minx;
void dfs(int x, int y, int len, int cnt) {
	if (x < 0 || y < 0 || x >= n || y >= m)return;
	if (len <= 0 || cnt >= minx)return;
	if (map[x][y] == 0)return;
	if (map[x][y] == 3) {
		if (cnt < minx)minx = cnt;
		return;
	}
	if (map[x][y] == 4) {
		len = 6;
	}
	if (cnt >= step[x][y] && time[x][y] >= len)return;
	step[x][y] = cnt;
	time[x][y] = len;
	int tx, ty, i;
	for (i = 0;i < 4;++i) {
		tx = x + go[i][0];
		ty = y + go[i][1];
		dfs(tx, ty, len - 1, cnt + 1);
	}
}
int main() {
	int t, i, j, len, cnt;
	cin >> t;
	while (t--) {
		cin >> n >> m;
		for (i = 0;i < n;++i) {
			for (j = 0;j < m;++j) {
				time[i][j] = 0;
				step[i][j] = 9999999;
				scanf("%d", &map[i][j]);
				if (map[i][j] == 2) {
					sx = i;
					sy = j;
				}
				else if (map[i][j] == 3) {
					dx = i;
					dy = j;
				}
			}
		}
		len = 6;
		cnt = 0;
		minx = 9999999;
		dfs(sx, sy, len, cnt);
		if (minx == 9999999) {
			cout << -1 << endl;
		}
		else {
			cout<

也是一道dfs的题目……多了一个重置时间的点,在代码中体现为多了一个if语句,不算太难,只要按照标准的dfs模板来写应该不会出现死循环(比如在重置时间点附近无限疯狂试探)

你可能感兴趣的:(HDU 1072)