经典算法<一>迷宫问题 4.多条路径 求路径条数求解 C++实现
2016-05-18 15:19
831 查看
/* * File name : maze_dual_path.cpp * Function : 迷宫多条路径求解 C++实现 * Created on : 2016年5月14日 * Author : beijiwei@qq.com * Copyright : 欢迎大家和我一起交流学习,转载请保持源文件的完整性。 任何单位和个人不经本人允许不得用于商业用途 说明: 1.第一条通路打通前,将不能到达的节点变为墙(0),分叉点变为 -1 2.第一次到达出口后,开始逆推,判断节点是否在打通的回路上,若是则 path增加1,遇到分叉点,分拆点变为1 3.本程序只能求 path 总数,待优化 */ #include <cstdio> #include <iostream> #pragma warning(disable:4996) using namespace std; typedef struct { int data; int x; int y; bool mark; }Spot; #define SIZE 10 Spot sarray[SIZE][SIZE]; Spot cross_store[20]; int cross_cursor = -1; void find(int x, int y, int fx, int fy); int path_count = 0; int main(int argc, char** argv) { int M = 0, N = 0; freopen("input.txt", "r", stdin); cin >> M >> N; for (int i = 0; i<M; i++) for (int j = 0; j < N; j++) { cin >> sarray[i][j].data; // get input data sarray[i][j].x = i; sarray[i][j].y = j; sarray[i][j].mark = false; } find(0, 0,0,0); cout<< "path count is : " << path_count << endl; return 0; } int get_pass_count(int x, int y) { int tmpx, tmpy, count = 0; int offset[4][2] = { -1,0,0,1,1,0,0,-1 }; for (int k = 0; k < 4; k++) { tmpx = x + offset[k][0]; tmpy = y + offset[k][1]; if (tmpx >= 0 && tmpx < SIZE && tmpy >= 0 && tmpy < SIZE && sarray[tmpx][tmpy].data == 1 && sarray[tmpx][tmpy].mark == false ) { count++; } } return count; } bool is_connect_to_path(int x, int y, int fx, int fy) { int tmpx, tmpy, count = 0; int offset[4][2] = { -1,0,0,1,1,0,0,-1 }; for (int k = 0; k < 4; k++) { tmpx = x + offset[k][0]; tmpy = y + offset[k][1]; if (tmpx >= 0 && tmpx < SIZE && tmpy >= 0 && tmpy < SIZE && sarray[tmpx][tmpy].data == -1 && sarray[tmpx][tmpy].mark == true ) { if (!(tmpx == fx && tmpy == fy)) count++; } } return (count >0) ? true : false; } bool get_first_flag = false; void find(int x, int y,int fx, int fy) { int tmpx, tmpy, count = 0; int offset[4][2] = { -1,0,0,1,1,0,0,-1 }; sarray[x][y].mark = true; cout << x << " " << y << endl; if (get_first_flag == true && is_connect_to_path(x, y,fx,fy)) { path_count++; } if (x == 9 && y == 9) { path_count++; get_first_flag = true; sarray[x][y].data = -2; } count = get_pass_count(x, y); if (count == 0) // no road { sarray[x][y].data = 0; } if(count > 1 ) // set cross data to -1 { sarray[x][y].data = -1; } if (count > 0) { for (int k = 0; k < 4; k++) { tmpx = x + offset[k][0]; tmpy = y + offset[k][1]; if (tmpx >= 0 && tmpx < SIZE && tmpy >= 0 && tmpy < SIZE && sarray[tmpx][tmpy].data == 1 && sarray[tmpx][tmpy].mark == false ) { find(tmpx,tmpy,x,y); } } if (get_pass_count(x, y) == 0) { sarray[x][y].data = 0; } } }
相关文章推荐
- 总结常出现的求sizeof值的情况
- C语言中内存分配
- 初学C和C++每日笔记 求个大神指点指路
- c++学习进阶方向
- 关于C++命名空间
- <dirent.h> in Visual C++
- 小飞机游戏C语言程序&划拳
- c++ primer 学习笔记(3): IO
- C++内存管理
- c语言链表和指针的运用
- C++ stringstream的用法
- 详解C++中StringBuilder类的实现及其性能优化
- C++ 生成写入字符
- 指针动态,分布与列表
- 用c++写一个 “hello,world” 的 FastCGI程序
- 彭界博-个人公寓管理系统
- C++ new/delete运算符
- C++ STL中哈希表 hash_map介绍
- ubuntu安装c/c++开发环境
- C++ num++书写位置影响其值的输出问题