| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 10380 | Accepted: 4485 |
Description
Input
Output
Sample Input
2 8 8 ######## #......# #.####.# #.####.# #.####.# #.####.# #...#..# #S#E#### 9 5 ######### #.#.#.#.# S.......E #.#.#.#.# #########
Sample Output
37 5 5 17 17 9
注意:
1.使用DFS计算左转优先和右转优先的路径,使用BFS计算最短路径
2.这里的DFS不需要标记,因为按照方向顺时针(或逆时针)前进时,除非无路可走才会返回,所以不会因为没有标记而出现问题,不过它的前进方向是相对,是相对当前位置进行左上右下(右前左后)探索(这个相对性非常重要),最初的方向由起点S确定,而下一步的方向则由前一步的走向决定
以顺时针,左手优先为例,即(相对于当前方向,左转90°后的方向为第一优先,依次右转90°找可能的通路)
如何左转90度?0,1,2,3代表四个方向,显示直接-1是不行的,可能变成负值了,那么可以用
(d+3)%4,就可以左转90度到优先位置,当然往右转的过程中,还是会超过0,1,2,3,到了外面,所以在运算时,使用d%4就可以了。
<pre name="code" class="html">#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <set>
#include <queue>
#include <stack>
using namespace std;
struct node {
int x,y;
int step;
};
char map[50][50];
int vis[50][50];
int jx[]= {0,1,0,-1};
int jy[]= {1,0,-1,0};
//设置为右上左下
int jr[]= {1,0,3,2};
int jl[]= {3,0,1,2};
int cnt,d;
char sx,sy,ex,ey;
int w,h;
void dfs_left(int d,int x,int y)
{
int i,j;
if(x==ex&&y==ey) {
printf("%d ",cnt);
return ;
}
cnt++;
for(j=0; j<4; j++) {
i=(d+jl[j])%4;
int dx=x+jx[i];
int dy=y+jy[i];
if(dx>=0&&dx<h&&dy>=0&&dy<w&&map[dx][dy]!='#') {
dfs_left(i,dx,dy);
return;
}
}
}
void dfs_right(int d,int x,int y)
{
int i,j;
if(x==ex&&y==ey) {
printf("%d ",cnt);
return ;
}
cnt++;
for(j=0; j<4; j++) {
i=(d+jr[j])%4;
int dx=x+jx[i];
int dy=y+jy[i];
if(dx>=0&&dx<h&&dy>=0&&dy<w&&map[dx][dy]!='#') {
dfs_right(i,dx,dy);
return;
}
}
}
void bfs(int x,int y)
{
int i;
memset(vis,0,sizeof(vis));
queue<node >q;
struct node t,f;
t.x=x;
t.y=y;
t.step=0;
q.push(t);
vis[t.x][t.y]=1;
while(!q.empty()) {
t=q.front();
q.pop();
if(t.x==ex&&t.y==ey) {
printf("%d\n",t.step+1);
return ;
}
for(i=0; i<4; i++) {
f.x=t.x+jx[i];
f.y=t.y+jy[i];
if(f.x>=0&&f.x<h&&f.y>=0&&f.y<w&&map[f.x][f.y]!='#'&&!vis[f.x][f.y]) {
vis[f.x][f.y]=1;
f.step=t.step+1;
q.push(f);
}
}
}
}
int main()
{
int T,i,j;
scanf("%d",&T);
while(T--) {
scanf("%d %d",&w,&h);
memset(vis,0,sizeof(vis));
for(i=0; i<h; i++) {
scanf("%s",map[i]);
for(j=0; j<w; j++) {
if(map[i][j]=='S') {
sx=i;
sy=j;
}
if(map[i][j]=='E') {
ex=i;
ey=j;
}
}
}
if(sx==0) d=0;
if(sx==h-1) d=2;
if(sy==0) d=1;
if(sy==w-1) d=3;
cnt=1;
dfs_left(d,sx,sy);
cnt=1;
dfs_right(d,sx,sy);
bfs(sx,sy);
}
return 0;
}
POJ 3083-Children of the Candy Corn(dfs+bfs)
原文:http://blog.csdn.net/u013486414/article/details/43866007