bzoj:1656 [Usaco2006 Jan] The Grove 树木
Description
The pasture contains a small, contiguous grove of trees that has no 'holes' in the middle of the it. Bessie wonders: how far is it to walk around that grove and get back to my starting position? She's just sure there is a way to do it by going from her start location to successive locations by walking horizontally, vertically, or diagonally and counting each move as a single step. Just looking at it, she doesn't think you could pass 'through' the grove on a tricky diagonal. Your job is to calculate the minimum number of steps she must take. Happily, Bessie lives on a simple world where the pasture is represented by a grid with R rows and C columns (1 <= R <= 50, 1 <= C <= 50). Here's a typical example where '.' is pasture (which Bessie may traverse), 'X' is the grove of trees, '*' represents Bessie's start and end position, and '+' marks one shortest path she can walk to circumnavigate the grove (i.e., the answer): ...+... ..+X+.. .+XXX+. ..+XXX+ ..+X..+ ...+++* The path shown is not the only possible shortest path; Bessie might have taken a diagonal step from her start position and achieved a similar length solution. Bessie is happy that she's starting 'outside' the grove instead of in a sort of 'harbor' that could complicate finding the best path.
Input
* Line 1: Two space-separated integers: R and C
* Lines 2..R+1: Line i+1 describes row i with C characters (with no spaces between them).
Output
* Line 1: The single line contains a single integer which is the smallest number of steps required to circumnavigate the grove.
Sample Input
.......
...X...
..XXX..
...XXX.
...X...
......*
Sample Output
随便找棵树然后画一条射线作为分界线,使之不能通过,然后就行BFS啦
以样例为例:
在第二行唯一一棵树那划条射线,然后BFS结果如下:(-1为树木,0为起点)
在这个数据里面并不明显,划过线的部分是不能通过的……
再看这个数据:
结果如下:
其他看代码咯
#include<queue> #include<cstdio> #include<algorithm> using namespace std; struct na{ int x,y; }; int n,m,x=-1,y; const int fx[8]={0,0,1,-1,1,1,-1,-1},fy[8]={1,-1,0,0,1,-1,1,-1}; int map[51][51]; char c; queue <na> q; int main(){ scanf("%d%d",&n,&m); for (int i=0;i<n;i++) for (int j=0;j<m;j++){ c=getchar(); while(c=='\n') c=getchar(); if (c=='X') { map[i][j]=-1; if (x==-1) x=i,y=j; }else if (c=='*'){ na tmp;tmp.x=i;tmp.y=j;q.push(tmp); }else map[i][j]=2500; } while(!q.empty()){ na k=q.front();q.pop(); for (int i=0;i<8;i++){ na now=k; now.x+=fx[i];now.y+=fy[i]; if (now.x<0||now.y<0||now.x>=n||now.y>=m) continue; if (k.y<=y&&k.x==x&&now.x==x-1) continue; if (k.y<=y&&k.x==x-1&&now.x==x) continue; if (map[now.x][now.y]>map[k.x][k.y]+1){ map[now.x][now.y]=map[k.x][k.y]+1; q.push(now); } } } int ans=2500; for (int i=y-1;i>=0;i--){ if (map[x][i]+map[x-1][i]<ans) ans=map[x][i]+map[x-1][i]; if (map[x][i]+map[x-1][i+1]<ans) ans=map[x][i]+map[x-1][i+1]; if (i) if (map[x][i]+map[x-1][i-1]<ans) ans=map[x][i]+map[x-1][i-1]; } printf("%d\n",ans+1); }