#include<stdio.h>
#include<vector>
#include<queue>
#include<iostream>
using namespace std;
#define INF 0x3f3f3f
#define MAXN 10
#define MAXM 10
#define MAXQ 101
int H[4]={0,1,0,-1};
int V[4]={-1,0,1,0};
struct Position{
int x,y;
Position(){
}
Position(int i,int j){
x=i;
y=j;
}
};
int n=7;
int m=7;
int grid[MAXN][MAXM]={
{0,0,1,1,0,0,0},{0,0,1,1,0,0,0},{0,0,1,1,0,0,0},{0,0,1,1,0,0,0}};
Position a(2,1),b(3,5);
int bestlen=INF;
vector<Position>bestpath;
int Count=0;
typedef struct {
int no;
Position p;
int length;
int pre;
}NodeType;
class QUEUE{
private:
NodeType data[MAXQ];
int front,rear;
public:
QUEUE(){
front=rear=-1;
}
bool empty(){
return front==rear;
}
void push(NodeType e){
rear++;
data[rear]=e;
}
NodeType pop(){
front++;
return data[front];
}
void GetPath(int s,vector<Position> & path){
int k=s;
while(k!=-1){
path.push_back(data[k].p);
k=data[k].pre;
}
}
};
void solve(){
NodeType e,e1;
Position p,p1;
QUEUE qu;
e.no=Count++;
e.pre=-1;
e.p=a;
e.length=0;
qu.push(e);
while(!qu.empty()){
e=qu.pop();
p=e.p;
if(p.x==b.x&&p.y==b.y){
if(e.length<bestlen){
bestlen=e.length;
bestpath.clear();
qu.GetPath(e.no,bestpath);
}
}else {
for(int j=0;j<4;j++){
p1.x=p.x+H[j];
p1.y=p.y+V[j];
if(p1.x>=0&&p1.x<n&&p1.y>=0&&p1.y<m&&grid[p1.x][p1.y]==0){
if(e.length+1<bestlen) {
e1.no=Count++;
e1.length=e.length+1;
e1.pre=e.no;
e1.p=p1;
qu.push(e1);
grid[p1.x][p1.y]=-1;
}
}
}
}
}
}
int main(){
solve();
cout<<bestlen<<endl<<"路径:";
vector<Position>::reverse_iterator it;
for(it=bestpath.rbegin();it!=bestpath.rend();it++){
printf("[%d,%d]",it->x,it->y);
}
cout<<endl;
}
求解布线问题(自定义队列)
最新推荐文章于 2023-11-07 20:29:29 发布