一:
问题描述,求从a走到b的最短路径
#include <iostream>
#include <cstring>
#include <queue>
#include <cstdlib>
using namespace std;
int dir[4][2] = {1,0,-1,0,0,1,0,-1};
const int maxn = 100;
class Position{
public:
Position(int a,int b){
r = a,c = b;
}
friend bool FindPath(Position &start,Position &finish,int p[maxn][maxn]);
int r;
int c;
};
bool FindPath(Position &start,Position &finish,int p[maxn][maxn]){
queue<Position>Q;
Q.push(start);
p[start.r][start.c] = 1;
cout<<start.r<<endl;
cout<<start.c<<endl;
cout<<finish.r<<endl;
cout<<finish.c<<endl;
for(int i = 0; i <= 10;i++){
for(int j = 0;j <=11;j++)
cout<<p[i][j]<<" ";
cout<<endl;
}
bool T = true;
int dr,dc;
int tr,tc;
int length = 0;
while(T){
Position tmp = Q.front();
Q.pop();
for(int i = 0;i < 4;i++){
dr = tmp.r+ dir[i][0];
dc = tmp.c+ dir[i][1];
if(dr == finish.r && dc == finish.c){
p[dr][dc] = p[tmp.r][tmp.c]+1;
length = p[tmp.r][tmp.c]-1;
cout<<"¾¹ý"<<length<<"¸öµã"<<endl;
T = false;
break;
}
else if(p[dr][dc] == 0){
p[dr][dc] = p[tmp.r][tmp.c]+1;
Position N(dr,dc);
Q.push(N);
}
}
if(Q.empty())
return false;
} for(int i = 0; i <= 7;i++){
for(int j = 0;j <=8;j++)
cout<<p[i][j]<<" ";
cout<<endl;
}
cout<<endl<<endl;
int **path;
path = new int*[length+1];
for(int i = 0;i <= length;i++)
path[i] = new int[2];
int t = length;
bool PID = true;
while(PID){
PID = false;
for(int i = 0;i < 4;i++){
tr = dr + dir[i][0];
tc = dc + dir[i][1];
if(p[tr][tc] == p[dr][dc] - 1){
dr = tr,dc = tc;
path[t][0] = tr;
path[t][1] = tc;
t--;
PID = true;
break;
}
}
if(!t)
break;
}
for(int i = 1;i <= length;i++)
cout<<path[i][0]<<" "<<path[i][1]<<endl;
return true;
}
int main(){
int pt[maxn][maxn];
memset(pt,0,sizeof pt);
int n = 20,m = 30,t;
for(int i = 0; i <= n+1;i++)
pt[i][0] = pt[i][m+1] = 1;
for(int i = 0;i <= m+1;i++)
pt[0][i] = pt[n+1][i] = 1;
int point[14][2] = {1,3,2,3,2,4,3,5,4,4,4,5,5,1,5,5,6,1,6,2,6,3,7,1,7,2,7,3};
for(int i = 0;i < 13;i++){
int u = point[i][0];
int v = point[i][1];
pt[u][v] = 1;
}
/*
cin>>t;
for(int i = 0; i < t;i++){
int u,v;
cin>>u>>v;
pt[u][v] = 1;
}
*/
Position s(3,2);
Position f(4,6);
FindPath(s,f,pt);
}