标签:
You have a maze with obstacles and non-zero digits in it:
You can start from any square, walk in the maze, and finally stop at some square. Each step, you may only walk into one of the four neighbouring squares (up, down, left, right) and you cannot walk into obstacles or walk into a square more than once. When you finish, you can get a number by writing down the digits you encounter in the same order as you meet them. For example, you can get numbers 9784, 4832145 etc. The biggest number you can get is 791452384, shown in the picture above.
Your task is to find the biggest number you can get.
3 7 ##9784# ##123## ##45### 0 0
791452384
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <vector> #include <string> #include <queue> using namespace std; const int N = 35; int n,m,MAX; char mp[N][N]; bool flag[N][N]; bool vis[N][N]; int dir[][2] = {{1,0},{-1,0},{0,-1},{0,1}}; struct Node{ int x,y; }; char res[N],ans[N],ans1[N]; bool check(int x,int y){ if(x<1||x>n||y<1||y>m||mp[x][y]==‘#‘) return false; return true; } Node q[N * N]; int bfs(int x,int y){ memset(flag,0,sizeof(flag)); int head = 0, tail = 0,ret = 0;; q[tail].x = x; ///手动队列非常快 q[tail++].y = y; flag[x][y] = true; while(head!= tail){ int nowx = q[head].x; int nowy = q[head++].y; for(int i=0;i<4;i++){ int nextx = nowx+dir[i][0]; int nexty = nowy+dir[i][1]; if(!check(nextx,nexty)||flag[nextx][nexty]||vis[nextx][nexty]) continue; ret++; flag[nextx][nexty] = true; q[tail].x = nextx; q[tail++].y = nexty; } } return ret; } void dfs(int x,int y,int step){ if(step>MAX||step==MAX&&strcmp(ans,res)>0){ MAX = step; strcpy(res,ans); } int GO = bfs(x,y); ///预处理最好的情况,所有点都可达 strcpy(ans1,ans); ans1[step] = ‘9‘; if(GO+step<MAX||GO+step==MAX&&strcmp(ans1,res)<0) return; ///剪枝,(x,y)能够走的距离 < 答案 for(int i=0;i<4;i++){ int nextx = x+dir[i][0]; int nexty = y+dir[i][1]; if(!check(nextx,nexty)||vis[nextx][nexty]) continue; vis[nextx][nexty] = true; ans[step] = mp[nextx][nexty]; dfs(nextx,nexty,step+1); ans[step] = 0; vis[nextx][nexty] = false; } } int main() { freopen("f.in","r",stdin); freopen("f.txt","w",stdout); while(scanf("%d%d",&n,&m)!=EOF,n+m){ int tot = 0; for(int i=1;i<=n;i++){ scanf("%s",mp[i]+1); for(int j=1;j<=m;j++){ if(mp[i][j]!=‘#‘) tot++; } } memset(res,0,sizeof(res)); MAX = -1; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(mp[i][j]==‘#‘||MAX==tot&&mp[i][j]<res[0]) continue; memset(vis,false,sizeof(vis)); ans[0] = mp[i][j]; vis[i][j] = true; dfs(i,j,1); } } printf("%s\n",res); } return 0; } /** 5 6 245356 342534 534635 423535 324345 */
湖南省第六届省赛题 Biggest Number (dfs+bfs,好题)
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5797714.html