CodeForces 589J Cleaner Robot (DFS,或BFS)

时间:2022-10-06 03:10:27

题意:给定n*m的矩阵,一个机器人从一个位置,开始走,如果碰到*或者边界,就顺时针旋转,接着走,问你最后机器人最多能走过多少格子。

析:这个题主要是题意读的不大好,WA了好几次,首先是在*或者边界才能转向,其次就是走过的地方也能走,注意这两点,就可以AC了,可以用DFS,也可以用BFS,

我用的DFS。

代码如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <stack>
using namespace std ; typedef long long LL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 10 + 5;
const int mod = 1e9 + 7;
const char *mark = "+-*";
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
int n, m;
inline bool is_in(int r, int c){
return r >= 0 && r < n && c >= 0 && c < m;
}
char s[15][15];
int vis[15][15];
int cnt; void dfs(int r, int c, int ok){
if(s[r][c] == '*' || cnt > 5000) return ;
++cnt;
for(int i = 0; i < 4; ++i){
int x = r + dr[(i+ok)%4];
int y = c + dc[(i+ok)%4];
if(is_in(x, y) && s[x][y] != '*'){
vis[x][y] = 1;
dfs(x, y, (ok+i)%4);
return ;
}
}
return ;
} int main(){
while(scanf("%d %d", &n, &m) == 2){
cnt = 0;
memset(s, 0, sizeof(s));
memset(vis, 0, sizeof(vis));
for(int i = 0; i < n; ++i)
scanf("%s", s[i]);
int sx, sy;
for(int i = 0; i < n; ++i)
for(int j = 0; j < m; ++j)
if(s[i][j] == 'U' || s[i][j] == 'D' || s[i][j] == 'L' || s[i][j] == 'R') sx = i, sy = j; vis[sx][sy] = 1;
if(s[sx][sy] == 'U') dfs(sx, sy, 0);
else if(s[sx][sy] == 'R') dfs(sx, sy, 1);
else if(s[sx][sy] == 'D') dfs(sx, sy, 2);
else if(s[sx][sy] == 'L') dfs(sx, sy, 3);
int ans = 0;
for(int i = 0; i < n; ++i)
for(int j = 0; j < m; ++j)
ans += vis[i][j];
printf("%d\n", ans);
}
return 0;
}