青蛙救公主,有小怪。。网上有说“记忆化bfs”,其实就是记录前驱。。。
以后用string记录路径,简单又方便。。。
5 6
.XX.1.
..X.2.
2...X.
...XX.
XXXXX.
#include<iostream> //有怪兽,访问条件为你的时间比这个节点此刻的小。同时用“记忆化BFS”,记录很早以前
#include<queue> //就见过的 /前驱 。然后再逆转。。
#include<cctype>
using namespace std;
#define MAXSIZE 100
#define INF 10000
struct node
{
int x,y;
}now,init={0,0},go;
struct point
{
int prex;
int prey;
int minstep;
char ch;
}Maze[MAXSIZE][MAXSIZE];
//Maze[0][0].minstep = 0;//
int N,M,HP;
queue<node> Q;
int dx[] = {-1,0,1,0};
int dy[] = {0,1,0,-1};
bool can(int x,int y)
{
if(x<0||x>N-1||y<0||y>M-1)
return false ;
if(Maze[x][y].ch=='X' )
return false ;
return true ;
}
int value(int x,int y)
{
if(Maze[x][y].ch=='.' )
return 1;
if(isdigit(Maze[x][y].ch))
return Maze[x][y].ch-'0' +1;
}
void BFS()
{
for(int j=0;j<N;++j)
for(int k=0;k<M;++k)
Maze[j][k].minstep = INF;
Maze[0][0].minstep = 0;
int x_now,y_now,x_next,y_next;
Q.push(init);
while(!Q.empty())
{
now = Q.front();Q.pop();
x_now = now.x;
y_now = now.y;
for(int i=0;i<4;++i)
{
x_next = x_now+dx[i];
y_next = y_now+dy[i];
if(can(x_next,y_next)&&
Maze[x_now][y_now].minstep+value(x_next,y_next)<Maze[x_next][y_next].minstep)
{
Maze[x_next][y_next].minstep = Maze[x_now][y_now].minstep+value(x_next,y_next);
Maze[x_next][y_next].prex = x_now;
Maze[x_next][y_next].prey = y_now;
go.x = x_next;
go.y = y_next;
Q.push(go);
}
}
}
}
int main()
{
while(cin>>N>>M)
{
for(int j=0;j<N;++j){
for(int k=0;k<M;++k)
cin>>Maze[j][k].ch;}
BFS();
if(Maze[N-1][M-1].minstep!=INF)
cout<< "the step is : "<<Maze[N-1][M-1].minstep<<endl;
else cout<<"Poor hero..." <<endl;
}
return 0;
}
逆序打印数组:
void reverse_print(int n)
{
if(n==sizeof(a)-1) printf("%d",a[n]);
else
{
reverse_print(n+1);
printf("%d",a[n]);
}
}
逆序打印上面的逆序数组:
貌似是一样的。。链表也是。。