http://acm.hdu.edu.cn/showproblem.php?pid=4771
题目意思就是给一个矩阵,“#”表示不可走,“.”表示可走,其重要遍历最多四个点,对少个点题目中给出,点的左边对应的符号肯定是“.”.
这其实就是一个简单的BFS,用2^4次方中状态表示访问先后顺序。其他的就没啥说的了。0ms 过;
#include <iostream> #include <queue> #include <cstdio> #include <stdlib.h> #include <memory.h> #define maxn 105 using namespace std; struct status { int x,y,step,shunxu; }now,change; char flag[maxn][maxn]; char map[maxn][maxn][16]; int row,col,num; struct point { int x,y; }number[5]; bool check(int x,int y,status now) { bool biaoji=0; if(x>=1&&x<=row&&y>=1&&y<=col) { if(map[y][x][now.shunxu]!='#'&&flag[y][x]!='#') { change=now,biaoji=1; change.x=x,change.y=y,change.step++; map[y][x][now.shunxu]='#'; for(int i=0;i<num;i++) { if(number[i].x==x&&number[i].y==y) { change.shunxu=change.shunxu|1<<i; map[y][x][change.shunxu]='#'; break; } } } } return biaoji; } int BFS(status &now) { queue<status>Q; Q.push(now); while(!Q.empty()) { now=Q.front(); Q.pop(); if(check(now.x+1,now.y,now)) { if(change.shunxu+1==1<<num)return change.step; Q.push(change); } if(check(now.x,now.y+1,now)) { if(change.shunxu+1==1<<num)return change.step; Q.push(change); } if(check(now.x-1,now.y,now)) { if(change.shunxu+1==1<<num)return change.step; Q.push(change); } if(check(now.x,now.y-1,now)) { if(change.shunxu+1==1<<num)return change.step; Q.push(change); } } return -1; } int main() { //freopen("in.txt","r",stdin); int locatex,locatey; while(~scanf("%d%d",&col,&row)&&!(col==0&&row==0)) { memset(number,0,sizeof number); memset(map,0,sizeof map); memset(flag,0,sizeof flag); getchar(); now.step=0; now.shunxu=0; for(int i=1;i<=col;i++) { for(int j=1;j<=row;j++) { scanf("%c",&map[i][j][0]); flag[i][j]=map[i][j][0]; if(map[i][j][0]=='@')now.x=j,now.y=i; } getchar(); } scanf("%d",&num); for(int i=0;i<num;i++)scanf("%d%d",&number[i].y,&number[i].x); cout<<BFS(now)<<endl; } }