布线问题

布线问题



<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[n][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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值