您的位置:首页 > 其它

784 - Maze Exploration(bfs)

2014-02-12 20:38 323 查看
题目:784 - Maze Exploration

题目大意:类似走迷宫, 八个方向走,空格的表示可以走,‘X’不可以走,‘*’是起点。

解题思路:BFS;

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;

const int N = 35;
const int M = 85;
int t, k;

char maze
[M];
int visit
[M];

int dir[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
struct node {

int x, y;
};
queue<node> q;

void bfs(int x, int y) {

visit[x][y] = 1;
maze[x][y] = '#';
node n;
n.x = x;
n.y = y;
q.push(n);
while(!q.empty()) {

n = q.front();
q.pop();
for(int i = 0; i < 8; i++) {

int x = n.x + dir[i][0];
int y = n.y + dir[i][1];
if(x >= 0 && x < k && y >= 0 && y < strlen(maze[x])) {

if(maze[x][y] == ' ' && !visit[x][y]) {

visit[x][y] = 1;
maze[x][y] = '#';
node n1;
n1.x = x;
n1.y = y;
q.push(n1);
}

}
}

}

}

int main() {

scanf("%d%*c", &t);
while(t--) {

memset(maze, 0, sizeof(maze));
memset(visit, 0, sizeof(visit));
k = 0;
while(gets(maze[k])) {

if(maze[k][0] == '_')
break;
k++;
}
int i, j;
for(i = 0; i < k; i++)  {

for(j = 0; j < strlen(maze[i]); j++)
if(maze[i][j] == '*')
break;
if(maze[i][j] == '*')
break;
}

bfs(i, j);
for(i = 0; i <= k; i++)
printf("%s\n", maze[i]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: