这道题麻烦一些。就是一个扫地机器人,遇到障碍会右转,问最多会清扫多少地方。如果它进入一个胡同,会困在那里,所以要判断是不是被困住了。
细节见代码。
#include<stdio.h>
#include<iostream>
#include<math.h>
#include<string.h>
#include<iomanip>
#include<stdlib.h>
#include<ctype.h>
#include<algorithm>
#include<deque>
#include<functional>
#include<iterator>
#include<vector>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<sstream>
#define CPY(A,B)memcpy(A,B,sizeof(A))
typedef long long LL;
typedef unsigned long long uLL;
const int MOD=1e9+7;
const int INF=0x3f3f3f3f;
const LL INFF=0x3f3f3f3f3f3f3f3fLL;
const double EPS=1e-9;
const double OO=1e20;
const double PI=acos (-1.0);
int dx[]= {-1,0,1,0};
int dy[]= {0,1,0,-1};
int gcd (const LL &a,const LL &b) {return b==0?a:gcd (b,a%b);}
using namespace std;
int w,h,sx,sy,dir,ans;
char m[12][12];
bool vis[12][12][4];
void ss (int sx,int sy,int dir) {
if (m[sx][sy]=='.') {ans++; m[sx][sy]='#';}//如果没清扫过,ans加一,清扫过后,改变那一位置的状态
for (int i=0; i<4; ++i) {
int x=sx+dx[ (i+dir) %4];
int y=sy+dy[ (i+dir) %4];
if (x<w&&x>=0&&y<h&&y>=0&&m[x][y]!='*') {
if (vis[x][y][ (i+dir) %4]==true) {break;}//再经过一点,如果和初次经过时的方向是一致的,说明陷入了重复,不必继续搜索
vis[x][y][ (i+dir) %4]=true;//记录位置和方向
ss (x,y, (i+dir) %4);//从当前位置继续搜
break;
}
}
}
int main() {
scanf ("%d%d",&w,&h);
memset (vis,0,sizeof vis);
for (int i=0; i<w; ++i) {
scanf ("%s",m[i]);
for (int j=0; j<h; ++j) {
if (isalpha (m[i][j]) ) {
sx=i,sy=j;//记录起始位置
if (m[i][j]=='U') {dir=0;}//将方向转换为数字,更方便解题
if (m[i][j]=='R') {dir=1;}
if (m[i][j]=='D') {dir=2;}
if (m[i][j]=='L') {dir=3;}
}
}
}
ans=1;
ss (sx,sy,dir);
printf ("%d\n",ans);
return 0;
}