不相交集类应用:迷宫生成
2012-10-07 14:54
295 查看
#include <iostream> #include <vector> #include <cstdlib> #include <ctime> #define N 100 using namespace std; int wall_row[N+1] ; int wall_col [N+1]; class DisjSets { public: explicit DisjSets(int numElements); int find(int x) const; void unionSets(int node1, int node2); bool connected(int node1, int node2) const { return find(node1) == find(node2); } private: vector<int> s; }; DisjSets::DisjSets(int numElements):s(numElements) { for (int i = 0; i < s.size(); i++) s[i] = -1; } int DisjSets::find(int x) const { if (s[x] < 0) return x; else return find(s[x]); } void DisjSets::unionSets(int node1, int node2) { int root1 = find(node1); int root2= find(node2); if (root1==root2) return; if (s[root2] < s[root1]) s[root1] = root2; else { if(s[root1] == s[root2]) s[root1]--; s[root2] = root1; } } void fill(int value) { int i,j; for(i=0; i<N+1; i++) for(j=0; j<N; j++) wall_row[i][j] = value; for(i=0; i<N; i++) for(j=0; j<N+1; j++) wall_col[i][j] = value; } void print() { int i, j; for (i=0; i<N+1; i++) { for (j=0; j<N+1; j++) { if (i > 0) { if(wall_col[i-1][j]) cout<<"|"; else cout<<" "; } if (j<N) { if (i>0) { if (wall_row[i][j]) cout<<"_"; else cout<<" "; } else { if(wall_row[i][j]) cout<<" _"; else cout<<" "; } } } cout<<endl; } } void map_rand(int x, int &type, int &a, int &b) { type = 0; if(x >= N*(N-1)) type = 1; if(type == 0) { a = x / (N - 1); b = x % (N - 1) + 1; } else { x -= N*(N-1); a = x / N + 1; b = x % N; } } void map_pos(int type, int a, int b, int &node1, int &node2) { if(type == 0) { node1 = a * N + b - 1; node2 = a * N + b; } else { node1 = (a - 1) * N + b; node2 = (a - 1) * N + b + N; } } int randselect(void) { int range = N*(N-1)*2; return rand() % range; } int main() { fill(1); //赋值全部为1 srand(time(0)); wall_row[0][0] = 0; wall_col[0][0] = 0; wall_row [N-1] = 0; wall_col[N-1] = 0;//定义出口入口 int amount = N * N; DisjSets s(amount); while(!s.connected(0, amount-1)) //是否两个节点相连(相同) { int type, a, b; do { int wall = randselect(); map_rand(wall, type, a, b); } while ((type == 0 && wall_col[a][b] == 0) ||(type == 1 && wall_row[a][b] == 0)) ; int node1, node2; map_pos(type, a, b, node1, node2); if(!s.connected(node1, node2)) { if(type == 0) wall_col[a][b] = 0; else wall_row[a][b] = 0; s.unionSets(node1, node2); } } print(); return 0; }
生成结果“
相关文章推荐
- 不相交集类以及应用迷宫生成
- 应用不相交集类生成迷宫
- 不相交类集算法生成迷宫并求解路径
- 用不相交集数据结构生成迷宫
- 用不相交集合生成一个迷宫
- 利用不相交集类制作迷宫游戏(数据结构课程设计——迷宫老鼠)
- Java 生成 XML文件 应用示例
- java web应用中自动生成文章html页面的实现
- Java应用iText动态生成PDF文件-温柔一刀
- Dockerfile生成镜像并实现应用自启
- PHP树生成迷宫及A*自己主动寻路算法
- 迷宫问题:hdoj1242--BFS基本应用
- 生成迷宫的程序
- C#迷宫生成的算法 --转
- 应用中验证码的生成方法.
- 让Eclipse编译应用时自动生成.apk文件
- 「两个指针的应用」最短摘要的生成
- 使用JFreeChart生成饼图,不做任何注释,只求应用,生成的饼图放在D:\\fruit.jpg
- jmacick生成不同尺寸图片的应用
- 减一技术应用:生成排列与幂集(Java实现)