POJ-3083 Children of the Candy Corn
2016-06-02 16:13
393 查看
题目大意:有一个迷宫,求从起点到终点以三种方式移动(贴左墙走、贴右墙走、最短)的距离
题目链接:http://poj.org/problem?id=3083
贴墙走用DFS,最短路用BFS
题目链接:http://poj.org/problem?id=3083
贴墙走用DFS,最短路用BFS
#include <iostream> #include <stdio.h> #include <string.h> #include <queue> #define MAXN 41 using namespace std; char maze[MAXN][MAXN]; int T; int w, h; int sx, sy, ex, ey; int dirx[] = { 0, -1, 0, 1 }; int diry[] = { -1, 0, 1, 0 }; //L,U,R,D struct Location{ int x, y, step; Location(){} Location(int xx, int yy, int ss) :x(xx), y(yy), step(ss){} }; void DFS(int x, int y, int& step, int face, int rule) { for (int i = 0; i < 4; i++) { int index, xx, yy; if (rule == 1)//left index = (face + 3 + i) % 4; else//right index = (face + 5 - i) % 4; xx = x + dirx[index]; yy = y + diry[index]; if (xx == ex && yy == ey) { step++; break; } else if (xx < 0 || xx >= h || yy < 0 || yy >= w) continue; else if (maze[xx][yy] == '#') continue; else { DFS(xx, yy, ++step, index, rule); break; } } } int BFS() { bool vis[MAXN][MAXN]; memset(vis, 0, sizeof(vis)); vis[sx][sy] = true; queue<Location> q; q.push(Location(sx, sy, 1)); while (!q.empty()) { Location p = q.front(); q.pop(); if (p.x == ex && p.y == ey) return p.step; for (int i = 0; i < 4; i++) { Location tmp(p.x + dirx[i], p.y + diry[i], p.step + 1); if (tmp.x < 0 || tmp.x >= h || tmp.y < 0 || tmp.y >= w) continue; if (maze[tmp.x][tmp.y] != '#'&&!vis[tmp.x][tmp.y]) { q.push(tmp); vis[tmp.x][tmp.y] = true; } } } } int main(int argc, char** argv) { scanf("%d", &T); while (T--) { scanf("%d%d", &w, &h); for (int i = 0; i < h; i++) { scanf("%s", maze[i]); for (int j = 0; j < w; j++) { //scanf(" %c", &maze[i][j]); if (maze[i][j] == 'S') { sx = i; sy = j; } else if (maze[i][j] == 'E') { ex = i; ey = j; } } } int face; if (sx == 0) face = 3; else if (sx == h - 1) face = 1; else if (sy == 0) face = 2; else face = 0; int step = 1; DFS(sx, sy, step, face, 1); printf("%d ", step); step = 1; DFS(sx, sy, step, face, 0); printf("%d ", step); printf("%d\n", BFS()); } return 0; }
相关文章推荐
- 初学ACM - 组合数学基础题目PKU 1833
- POJ ACM 1001
- POJ ACM 1002
- 1611:The Suspects
- POJ1089 区间合并
- POJ 2159 Ancient Cipher
- POJ 2635 The Embarrassed Cryptographe
- POJ 3292 Semi-prime H-numbers
- POJ 2773 HAPPY 2006
- POJ 3090 Visible Lattice Points
- POJ-2409-Let it Bead&&NYOJ-280-LK的项链
- POJ-1695-Magazine Delivery-dp
- POJ1523 SPF dfs
- POJ-1001 求高精度幂-大数乘法系列
- POJ-1003 Hangover
- POJ-1004 Financial Management
- POJ1050 最大子矩阵和
- 用单调栈解决最大连续矩形面积问题
- 2632 Crashing Robots的解决方法
- 1573 Robot Motion (简单题)