采用队列式分支限界法
#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
*/