算法-分支限界法-布线问题

采用队列式分支限界法

#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
struct Block//方格位置类
{
	int col = 0;
	int row = 0;

	Block(int row = 0, int col = 0)
	{
		this->col = col;
		this->row = row;
	}
};
queue<Block> Q;
int Maze[101][101];
Block offset[4];
int C, R;
void Initial()
{
	printf("输入电路板的行数和列数\n");
	cin >> R >> C;
	printf("输入电路板的组成\n");
	for (int i = 1; i <= R; i++)
		for (int j = 1; j <= C; j++)
			cin >> Maze[i][j];
	for (int i = 0; i <= C; i++)
	{
		Maze[0][i] = 1;
		Maze[R + 1][i] = 1;
	}
	for (int i = 0; i <= R; i++)
	{
		Maze[i][0] = 1;
		Maze[i][C + 1] = 1;
	}
	Maze[R + 1][C + 1] = 1;
	offset[0].row = 1;
	offset[1].row = -1;
	offset[2].col = -1;
	offset[3].col = 1;
}
void Wiring(Block start, Block target)
{
	Maze[start.row][start.col] = 2;
	if ((start.col == target.col) && (start.row == target.row))
	{
		printf("线已经布好了\n");
		return;
	}
	Q.push(start);
	Block tmp;
	int Row, Col;
	while (!Q.empty())
	{
		tmp = Q.front();
		Q.pop();
		Row = tmp.row;
		Col = tmp.col;
		for (int i = 0; i < 4; i++)
		{
			if (Maze[Row + offset[i].row][Col + offset[i].col] == 0)
			{
				Q.push(Block(Row + offset[i].row, Col + offset[i].col));
				Maze[Row + offset[i].row][Col + offset[i].col] = Maze[Row][Col] + 1;
			}
			if (Row + offset[i].row == target.row && Col + offset[i].col == target.col)
			{
				printf("线已经布好了\n");
				return;
			}
		}
	}
}
void wire(Block start, Block target)
{
	for (int i = 0; i <= R + 1; i++)
	{
		for (int j = 0; j <= C + 1; j++)
			printf("%3d", Maze[i][j]);
		cout << endl;
	}
	printf("线路点如下\n");
	int Row, Col;
	Row = target.row;
	Col = target.col;
	while (!(Col == start.col && Row == start.row))
	{
		for (int i = 0; i < 4; i++)
		{
			if (Maze[Row][Col] - Maze[Row + offset[i].row][Col + offset[i].col] == 1 && Maze[Row + offset[i].row][Col + offset[i].col] != 0)
			{
				printf("(%d,%d) ", Row, Col);
				Col = Col + offset[i].col;
				Row = Row + offset[i].row;
				break;
			}
		}
	}
	printf("(%d,%d) ", Row, Col);
}
int main()
{
	Initial();
	Block Start;
	Block target;
	printf("输入布线的起点,第几行第几列\n");
	cin >> Start.row >> Start.col;
	printf("输入布线的终点,第几行第几列\n");
	cin >> target.row >> target.col;
	Wiring(Start, target);
	wire(Start, target);
	return 0;
}

/*
9 7
0 0 0 0 1 0 0
0 0 1 0 0 0 0
0 0 1 0 1 1 0
0 0 1 0 0 0 0
0 0 0 0 0 1 0
0 0 0 1 1 1 0
0 0 0 0 0 1 0
0 0 0 0 0 0 0
0 0 1 0 1 0 0
3 2
6 7

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值