您的位置:首页 > 其它

迷宫问题-POJ - 3984

2018-02-25 21:36 309 查看
题解:宽度优先搜索
AC代码:
#include <cstdio>
#include <queue>

using namespace std;

#define MAXN 5

#define STARTROW 1
#define STARTCOL 1
#define ENDROW MAXN
#define ENDCOL MAXN

#define DIRECTSIZE 4

struct direct {
int drow;
int dcol;
} direct[DIRECTSIZE] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};

int maze[MAXN+2][MAXN+2];

struct node {
int row;
int col;
};

node father[MAXN+2][MAXN+2];

queue<node> q;

void print_result()
{
node path[MAXN*MAXN];
int count = 0;

path[count].row = ENDROW;
path[count].col = ENDCOL;
for(;;) {
if(path[count].row == STARTROW && path[count].col == STARTCOL)
break;

path[count+1] = father[path[count].row][path[count].col];
count++;
}

while(count >= 0) {
printf("(%d, %d)\n", path[count].row-1, path[count].col-1);

count--;
}
}

void bfs()
{
node start;
start.row = STARTROW;
start.col = STARTCOL;
q.push(start);

while(!q.empty()) {
node front = q.front(); q.pop();
if (front.row == ENDROW && front.col == ENDCOL) {
print_result();
return;
}
for(int i=0; i<DIRECTSIZE; i++) {
int nextrow = front.row + direct[i].drow;
<
4000
span style="color:#cc7832;">int nextcol = front.col + direct[i].dcol;
if(maze[nextrow][nextcol] == 0) {
father[nextrow][nextcol] = front;
node v;
v.row = nextrow;
v.col = nextcol;
q.push(v);
}
}

maze[front.row][front.col] = 1;
}
}

int main(void)
{
int i, j;
for(i=0; i<MAXN+2; i++) {
maze[0][i] = 1;
maze[MAXN+1][i] = 1;
maze[i][0] = 1;
maze[i][MAXN+1] = 1;
}

for(i=1; i<=MAXN; i++)
for(j=1; j<=MAXN; j++)
scanf("%d", &maze[i][j]);

bfs();

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ACM