http://poj.org/problem?id=3984
#include <stdio.h> #include <iostream> #include <math.h> #include <stdlib.h> #include < ctype.h> #include <algorithm> #include <vector> #include <string.h> #include <queue> # include<stack> #include <set> #include <map> #include <sstream> #include <time.h> # include<utility> #include <malloc.h> #include <stdexcept> #include <iomanip> #include < Iterator> using namespace Std;int N, m;int p[35][35];int vis[6][6];int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, { 0,-1}};struct node{int x;int y;}; struct node pre[30][30];//storage node the previous position int check (int x, int y) {if (x >= 0 && x < 5 && y >= 0 &&am P Y < 5) return 1;return 0;} void Printf_path () {stack<node> path;//stack is used to save the path node ss;ss.x = 4;ss.y = 4;while (1) {Path.push (ss); if (!ss.x & &!ss.y) Break;ss = Pre[ss.x][ss.y];} while (!path.empty ()) {SS = Path.top ();p ath.pop ();p rintf ("(%d,%d) \ n", Ss.x,ss.y);}} void BFs () {memset (vis,0,sizeof (VIS)), queue <node> q;node qq, qqq;qq.x = 0;QQ.Y = 0;vis[0][0] = 1;q.push (QQ); while (! Q.empty ()) {QQ = Q.front (); Q.pop (); if (qq.x = = 4 && qq.y = 4) {Printf_path (); return;} for (int i = 0; i < 4;i++) {int x = qq.x + Dir[i][0];int y = qq.y + dir[i][1];if (!check (x, y) | | vis[x][y] | | p[x][y] = = 1) continue;qqq = qq;qqq.x = X;qqq.y = Y;pre[qqq.x][qqq.y] = qq;vis[x][y] = 1;q.push (QQQ);}} return;} int main () {for (int i = 0, i < 5; i++) {for (int j = 0; J < 5; J + +) {cin >> p[i][j];}} BFS (); return 0;}
poj-3084 Output Path of BFS