您的位置:首页 > 其它

布线问题

2016-06-02 20:34 155 查看
布线问题









<span style="font-size:14px;">#include<iostream>
#include<iomanip>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;

typedef struct Direct
{
int x;
int y;
};

typedef Direct Position;
class Buxian
{
public :
Buxian()
{
//方格阵列
cin >> n>>m;
vector<int> g1(m+1, -1);
grid.push_back(g1);
for (int i = 1; i <= n; i++)
{
vector<int> g2(m+1 , -2);
grid.push_back(g2);
}
//设“围墙”
for (int i = 0; i <= n; i++)
{
grid[i][0] = grid[i][m] = -1;
}
for (int i = 0; i <= m; i++)
{
grid[0][i] = grid
[i] = -1;
}
grid[5][1] = -1;
grid[6][1] = -1;
grid[7][1] = -1;

grid[6][2] = -1;
grid[7][2] = -1;

grid[1][3] = -1;
grid[2][3] = -1;
grid[6][3] = -1;
grid[7][3] = -1;

grid[2][4] = -1;
grid[4][4] = -1;

grid[3][5] = -1;
grid[4][5] = -1;
grid[5][5] = -1;

//方向数组
offset[0] = { 0 , 1};//右
offset[1] = { 1 , 0};//下
offset[2] = { 0 , -1 };//左
offset[3] = { -1  , 0};//上

//输入始点,终点,
cin >> start.x >>start.y;
cin >> end.x >> end.y;
}

void FindPath()
{
queue<Position> Q;
Position here, nbr;
here = start;
grid[here.x][here.y] = 0;
while (true)
{
for (int i = 0; i < 4; i++)
{
nbr.x = here.x + offset[i].x;
nbr.y = here.y + offset[i].y;
if (grid[nbr.x][nbr.y] == -2)//该方格未被标记
{
grid[nbr.x][nbr.y] = grid[here.x][here.y] + 1;
if (nbr.x == end.x && nbr.y == end.y) break;//完成布线
Q.push(nbr);
}
}
if (nbr.x == end.x && nbr.y == end.y) break;//完成布线
if (Q.empty())
{
cout << "wujie" << endl;
return;
}
here = Q.front();
Q.pop();//
}

pathlen = grid[end.x][end.y];
//从目标位置end开始向起始点回溯
path.assign(pathlen + 1, { 0 , 0 });
here = end;
for (int j = pathlen ; j >= 0; j--)
{
path[j] = here;
//找前驱位置
for (int i = 0; i < 4; i++)
{
nbr.x = here.x + offset[i].x;
nbr.y = here.y + offset[i].y;
if (grid[nbr.x][nbr.y] == j-1) break;//该方格未被标记
}
here = nbr;
}
}

void print()
{
cout << "grid :" << endl;
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= m; j++)
{
cout << setw(4)<<grid[i][j] << " ";
}
cout << endl;
}
cout << "path :" << endl;
for (int i = path.size()-1; i >= 0 ; i--)
{
cout << "( " << path[i].x << " , " << path[i].y << ")" << endl;
}
}
public:
vector<vector<int> > grid;//方格阵列
Direct offset[4];//方向数组
Position start, end;//始点,终点
vector<Position> path;
int pathlen = 0;
int n , m;
};

Buxian BX;

int main()
{
BX.FindPath();
BX.print();
return 0;
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: