布线问题
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>
相关文章推荐
- Android Studio[百度地图SDK开发](一)
- git ignore 已经添加在仓库中的文件
- 八皇后
- 关于Javascript对象的理解
- Linux下手动安装Apache2全过程
- Android Camera HAL3中拍照Capture模式下多模块间的交互与帧Result与帧数据回调
- Node入门学习——获取POST请求的参数
- java基础知识----API
- 第二阶段冲刺(第七天)
- java_randomAccessFile类的使用
- bootstrap modal使用感悟
- ionic 使用笔记(201606)
- leetcode 165
- Picasso入门教程(五) Placeholder,errors,Fading
- 学习数学系列<一>
- Java IO - DataInputStream&DataOutputStream
- 框架初始接触引入
- Dubbo+Zookeeper+Springmvc整合
- EJB是什么鸟东西?
- java基础知识---多线程、同步