P11228 [CSP-J 2024] 地图探险 题解

模拟

第一眼,可能有人回想起 dfs.

但因为起点终点,并且走的步数都告诉你了,所以直接模拟就行.

注意

起始点也算被走过,所以可以用一个标记数组,判断当前格子有没有被走过.

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // 方向,x,y
int T;
char a[1003][1003];
int n;
int m;
int k;
int d;
int x, y;

int main() {
	scanf("%d", &T);
	while (T--) {
		scanf("%d%d%d", &n, &m, &k);
		scanf("%d%d%d", &x, &y, &d);
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= m; j++)
				cin >> a[i][j];
		}
		bool vis[1003][1003];
		memset(vis, 0, sizeof(vis));
		int ans = 1; // 起始点也算被走过
		vis[x][y] = 1;
		for (int i = 1; i <= k; i++) {
			int nx = x + dir[d][0];
			int ny = y + dir[d][1];
            // 判断是否合法
			if (1 <= nx && nx <= n && 1 <= ny && ny <= m && a[nx][ny] != 'x') {
				if (!vis[nx][ny]) {
					ans++;
					vis[nx][ny] = 1;
				}
				x = nx, y = ny; // 更新坐标
			}
			else 
				d = (d + 1) % 4; // 更改方向
		}
		printf("%d\n", ans);
	}
	return 0;
}
posted @ 2024-11-01 12:33  Panda_LYL  阅读(1030)  评论(0)    收藏  举报