标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6048 Accepted Submission(s): 1729
/** 题意:如题 做法:bfs + dfs **/ #include <iostream> #include <stdio.h> #include <string.h> #include <cmath> #include <algorithm> #include <queue> #define maxn 10 #define INF 0x7fffffff using namespace std; int mmap[maxn][maxn]; int used[maxn][maxn]; int vis[maxn][maxn][maxn][maxn]; int n,m; int dx[4] = {0,0,-1,1}; int dy[4] = {1,-1,0,0}; bool flag = false; struct Node { int bx; int by; int mx; int my; int step; Node() {} Node(int _bx,int _by,int _mx,int _my,int _step) { bx = _bx; by = _by; mx = _mx; my = _my; step = _step; } }; int check(int x,int y) { if(x >= 0 && x < n && y >= 0 && y <m && mmap[x][y] != 1) return 1; return 0; } void dfs(int bx,int by,int mx,int my) { if(bx == mx && by == my) { flag = true; return ; } for(int i=0; i<4 && flag == false; i++) { int tx = bx + dx[i]; int ty = by + dy[i]; if(check(tx,ty)&&used[tx][ty] == 0) { used[tx][ty] = 1; dfs(tx,ty,mx,my); } } } void bfs(int bx,int by,int mx,int my) { queue<Node>que; while(!que.empty()) que.pop(); Node tmp,now; tmp = Node(bx,by,mx,my,0); //cout<<tmp.bx<<" "<<tmp.by<<" "<<tmp.mx<<" "<<tmp.my<<" "<<tmp.step<<endl; que.push(tmp); while(!que.empty()) { now = que.front(); que.pop(); if(mmap[now.bx][now.by] == 3) { printf("%d\n",now.step); return; } for(int i=0; i<4; i++) { tmp.bx = now.bx + dx[i]; tmp.by = now.by + dy[i]; tmp.mx = now.bx - dx[i]; tmp.my = now.by - dy[i]; if(check(tmp.bx,tmp.by) && check(tmp.mx,tmp.my) && vis[tmp.bx][tmp.by][tmp.mx][tmp.my] == 0) { memset(used,0,sizeof(used)); flag = false; used[now.bx][now.by] = 1; used[tmp.mx][tmp.my] = 1; dfs(tmp.mx,tmp.my,now.mx,now.my); if(flag == true) { vis[tmp.bx][tmp.by][tmp.mx][tmp.my] = 1; tmp.step = now.step + 1; que.push(tmp); } } } } printf("-1\n"); return ; } int main() { //#ifndef ONLINE_JUDGE // freopen("in.txt","r",stdin); //#endif // ONLINE_JUDGE int T; scanf("%d",&T); while(T--) { scanf("%d %d",&n,&m); int bx,by,mx, my; memset(vis,0,sizeof(vis)); memset(mmap,0,sizeof(mmap)); for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { scanf("%d",&mmap[i][j]); if(mmap[i][j] == 2) { bx = i; by = j; } if(mmap[i][j] == 4) { mx = i; my = j; } } } bfs(bx,by,mx,my); } return 0; }
标签:
原文地址:http://www.cnblogs.com/chenyang920/p/4546168.html