| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
BFS 依次遍历 难道得到的不是最短距离?求一个例子#include <iostream>
using namespace std;
struct Node{
int x, y;
int step;
};
struct Point{
int x, y;
};
Node queue[1024*1024];
Point Start;
Point p[25*25];
Point dir[4] = {0,1,1,0,0,-1,-1,0};
int top = 0;
int H, W;
char data[25][25];
int book[25][25];
int vis[25];
int dis[25][25];
int ans;
int bfs();
int isOk(int x, int y);
int main(int argc, char** argv)
{
int T, test_case;
freopen("input.txt", "r", stdin);
cin >> T;
for(test_case = 0; test_case < T; test_case++)
{
cin >> W >> H;
if (!W && !H) break;
top = 0;
//char tmp;
for (int i=0; i<H; i++){
for(int j=0; j<W; j++){
cin >> data[i][j];
//dis[i][j] = 0;
if (data[i][j] == 'o'){
Start.x = i;
Start.y = j;
top++;
}
else if(data[i][j] == '*'){
top++;
}
}
}
//cout << "top = "<< top << endl;
ans = 0;
for(int i=1; i<top; i++){
//printf("%d------->(%d, %d)\n",i, Start.x, Start.y);
int tmp = bfs();
if (tmp!=-1)
ans += tmp;
else {
ans = -1;
break;
}
//bfs();
//cout << ans << endl;
}
//printf("%d------->(%d, %d)\n",4, Start.x, Start.y);
cout << ans << endl;
}
return 0;
}
int bfs()
{
Node np, nep;
int head, tail;
head = tail =0;
for (int i=0; i<25; i++)
for (int j=0; j<25; j++)
book[i][j] = 0;
np.x = Start.x;
np.y = Start.y;
np.step = 0;
book[np.x][np.y] = 1;
queue[tail++] = np;
while (head < tail){
np = queue[head++];
if (data[np.x][np.y] == '*'){
data[Start.x][Start.y] = '.';
Start.x = np.x;
Start.y = np.y;
data[Start.x][Start.y] = '.';
return np.step;
}
for (int i=0; i<4; i++){
nep.x = np.x + dir[i].x;
nep.y = np.y + dir[i].y;
if (isOk(nep.x, nep.y) && data[nep.x][nep.y]!='x' && book[nep.x][nep.y]==0){
book[nep.x][nep.y] = 1;
nep.step = np.step + 1;
queue[tail++] = nep;
}
}
}
return -1;
}
int isOk(int x, int y)
{
if (x>=0 && x<H && y>=0 && y<W) return 1;
else return 0;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator