USACO 5.2 Snail Trails(DFS)
2015-03-29 21:56:23
思路:DFS搞之,类似记忆化搜索过程的写法,只不过没有记忆化。
需要注意的一个细节是:当且仅当碰到障碍或者出界才能转向。(碰到已经走过的格子就只能停下了,不能转向)
1 /* 2 ID:naturec1 3 PROG: snail 4 LANG: C++ 5 */ 6 #include <cstdio> 7 #include <cstring> 8 #include <cstdlib> 9 #include <cmath> 10 #include <vector> 11 #include <map> 12 #include <set> 13 #include <stack> 14 #include <queue> 15 #include <string> 16 #include <iostream> 17 #include <algorithm> 18 using namespace std; 19 20 #define MEM(a,b) memset(a,b,sizeof(a)) 21 #define REP(i,n) for(int i=0;i<(n);++i) 22 #define FOR(i,a,b) for(int i=(a);i<=(b);++i) 23 #define getmid(l,r) ((l) + ((r) - (l)) / 2) 24 #define MP(a,b) make_pair(a,b) 25 26 typedef long long ll; 27 typedef pair<int,int> pii; 28 const int INF = (1 << 30) - 1; 29 30 int n,m; 31 int g[130][130]; 32 bool vis[130][130]; 33 int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}}; 34 35 int Dfs(int x,int y,int pre){ 36 if(vis[x][y]) return 0; 37 vis[x][y] = 1; 38 int tx = x + dir[pre][0]; 39 int ty = y + dir[pre][1]; 40 int res = 0; 41 if(tx < 1 || tx > n || ty < 1 || ty > n || g[tx][ty]){ 42 REP(i,4){ 43 tx = x + dir[i][0]; 44 ty = y + dir[i][1]; 45 if(tx < 1 || tx > n || ty < 1 || ty > n || vis[tx][ty] || g[tx][ty]) 46 continue; 47 int cur = Dfs(tx,ty,i); 48 if(cur > 0) res = max(res,cur); 49 } 50 } 51 else res = Dfs(tx,ty,pre); 52 vis[x][y] = 0; 53 return res + 1; 54 } 55 56 int main(){ 57 freopen("snail.in","r",stdin); 58 freopen("snail.out","w",stdout); 59 char s[10]; 60 scanf("%d%d",&n,&m); 61 REP(i,m){ 62 scanf("%s",s); 63 int x = s[0] - 'A' + 1; 64 int y = 0; 65 int len = strlen(s); 66 for(int j = 1; j < len; ++j) y = y * 10 + s[j] - '0'; 67 g[y][x] = 1; 68 } 69 int ans = 0; 70 printf("%d\n",max(Dfs(1,1,1),Dfs(1,1,3))); 71 return 0; 72 }