POJ 3083 Children of the Candy Corn(BFS + DFS)

来源:互联网 发布:异地恋男友要分手知乎 编辑:程序博客网 时间:2024/06/02 16:46

优先左转 优先右转  两点最短

#include<iostream>#include<algorithm>#include<cstring>#include<string>#include<sstream>#include<queue>#include<cstdio>using namespace std;typedef long long LL;const int INF = 0x3f3f3f3f;const int M = 1010;int dir[][2] = { 0,-1,-1,0,0,1,1,0 };//L U R Dchar mp[50][50];struct  node{int x, y, f, step;bool operator <(const node &b)const{return step > b.step;}}st, nx, tmp;int n, m;int sx, sy;bool vis[55][55];priority_queue<node>q;int cnt;int bfs(){memset(vis, 0, sizeof(vis));while (!q.empty())    //清空啊 我日{q.pop();}st.x = sx;st.y = sy;st.step = 1;vis[sx][sy] = 1;q.push(st);cnt = INF;while (!q.empty()){nx = q.top();q.pop();if (mp[nx.x][nx.y] == 'E'){return nx.step;}for (int i = 0; i < 4; ++i){int xx = nx.x + dir[i][0];int yy = nx.y + dir[i][1];if (xx >= 0 && xx < n && yy >= 0 && yy < m && mp[xx][yy] != '#' && !vis[xx][yy]){vis[xx][yy] = 1;tmp.x = xx;tmp.y = yy;tmp.step = nx.step + 1;q.push(tmp);}}}return 0;}int dfs(int x, int y, int step, int f){if (mp[x][y] == 'E'){return step;}for (int i = 0; i < 4; ++i){int tmp = ((f - 1 + 4) % 4 + i) % 4;int xx = x + dir[tmp][0];int yy = y + dir[tmp][1];if (mp[xx][yy] != '#' && xx >= 0 && xx < n && yy >= 0 && yy < m){dfs(xx, yy, step + 1, tmp);break;}}}int dfs2(int x, int y, int step, int f){if (mp[x][y] == 'E'){return step;}for (int i = 0; i < 4; ++i){int tmp = ((f + 1) % 4 - i + 4) % 4;int xx = x + dir[tmp][0];int yy = y + dir[tmp][1];if (mp[xx][yy] != '#' && xx >= 0 && xx < n && yy >= 0 && yy < m){dfs2(xx, yy, step + 1, tmp);break;}}}int main(){int t;scanf("%d", &t);while (t--){scanf("%d%d", &m, &n);for (int i = 0; i < n; ++i){for (int j = 0; j < m; ++j){cin >> mp[i][j];if (mp[i][j] == 'S'){sx = i;sy = j;}}}int ans= bfs();int fx = 0;for (int i = 0; i < 4; ++i){if (mp[sx + dir[i][0]][sy + dir[i][1]] == '.'){fx = i;break;}}int ans1 = dfs(sx, sy, 1, fx);//cout << ans1 << endl;int ans2 = dfs2(sx, sy, 1, fx);//cout << ans2 << endl;printf("%d %d %d\n", ans1, ans2, ans);}return 0;}



0 0
原创粉丝点击