题意:一个矩阵表示一个迷宫,0表示可通过,1表示不能通过,输出从左上角到右下角的最短路径
链接:http://poj.org/problem?id=3984
思路:bfs记录时间+dfs输出路径
注意点:无
以下为AC代码:
Run ID | User | Problem | Result | Memory | Time | Language | Code Length | Submit Time |
13918884 | luminous11 | 3984 | Accepted | 744K | 0MS | G++ | 2096B | 2015-02-28 17:08:36 |
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <deque>
#include <list>
#include <cctype>
#include <algorithm>
#include <climits>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#define ll long long
#define ull unsigned long long
#define all(x) (x).begin(), (x).end()
#define clr(a, v) memset( a , v , sizeof(a) )
#define pb push_back
#define mp make_pair
#define read(f) freopen(f, "r", stdin)
#define write(f) freopen(f, "w", stdout)
using namespace std;
const double pi = acos(-1);
int dir[4][2] = { 0,1, 0,-1, 1,0, -1,0 };
struct node{
int x, y;
int cnt;
node(){}
node( int _x, int _y, int _cnt ) : x(_x), y(_y), cnt(_cnt){}
};
int path[10][10];
int dis[10][10];
bool flag = 1;
bool init(){
memset ( path, 0x3f3f3f, sizeof ( path ) );
memset ( dis, 0x3f3f3f, sizeof ( dis ) );
flag = 0;
for ( int i = 1; i < 6; i ++ ){
for ( int j = 1; j < 6; j ++ ){
cin >> path[i][j];
}
}
return true;
}
int bfs (){
queue<node> q;
q.push( node(1,1,1) );
while ( ! q.empty() ){
node tmp = q.front();
dis[tmp.x][tmp.y] = tmp.cnt;
q.pop();
for ( int i = 0; i < 4; i ++ ){
if ( path[tmp.x+dir[i][0]][tmp.y+dir[i][1]] == 0 &&
dis[tmp.x+dir[i][0]][tmp.y+dir[i][1]] >= dis[tmp.x][tmp.y] ){
q.push ( node( tmp.x+dir[i][0], tmp.y+dir[i][1], tmp.cnt + 1 ) );
}
}
}
}
void dfs ( int x, int y ){
if ( x == 1 && y == 1 )flag = 1;
for ( int i = 0; i < 4; i ++ ){
if ( dis[x+dir[i][0]][y+dir[i][1]] < dis[x][y] ){
dfs ( x + dir[i][0], y + dir[i][1] );
}
if ( flag ){
cout << '(' << x-1 << ", " << y-1 << ')' << endl;
return;
}
}
}
int main()
{
ios::sync_with_stdio( false );
init();
bfs();
dfs( 5,5 );
return 0;
}