Uva - 1600 - Patrol Robot


dfs和bfs都能做,我用dfs遍历了,dfs应该要快,我AC了之后找了找网上bfs写的,时间是我的9倍以上,都比较慢,所以用dfs还是很不错的,注意递归的条件。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <stack>
#include <queue>
#include <bitset> 
#include <cassert> 
#include <cmath>

using namespace std;

const int maxn = 30;
int m, n, k;
int grid[maxn][maxn];
int state[21][21][21];
int ans;

int dr[] = { -1, 1, 0, 0 };
int dc[] = { 0, 0, -1, 1 };

// dfs递归,从(x,y)出发,当前走了cnt步,已经连续穿越了haveCross层墙
void dfs(int x, int y, int cnt, int haveCross)
{
	if (x == m - 1 && y == n - 1) {
		ans = min(ans, cnt);
		return;
	}
	for (int i = 0; i < 4; i++) {
		int x1 = x + dr[i];
		int y1 = y + dc[i];
		int c = haveCross;
		if (grid[x1][y1] == 1) {
			c++;
		}
		else {
			c = 0;
		}
		if (x1 >= 0 && x1 < m && y1 >= 0 && y1 < n) {
			if ((state[x1][y1][c] < 0 ||
				state[x1][y1][c] > cnt + 1) &&
				c <= k) { // 走到下一步的时候,之前走到这里的步数必须小于之后走到这里的步数。
				state[x1][y1][c] = cnt + 1;
				dfs(x1, y1, cnt + 1, c);
			}
		}
	}
	return;
}


int main()
{
	ios::sync_with_stdio(false);
	int T;
	cin >> T;
	while (T--) {
		memset(state, -1, sizeof(state));
		ans = 1 << 30;
		//cout << ans;
		cin >> m >> n >> k;
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				cin >> grid[i][j];
			}
		}
		dfs(0, 0, 0, 0);
		if (ans != 1 << 30) {
			cout << ans << endl;
		}
		else {
			cout << "-1\n";
		}
	}

	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值