算法————回溯法--迷宫问题(残缺)
Posted zlshy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法————回溯法--迷宫问题(残缺)相关的知识,希望对你有一定的参考价值。
#include<iostream> using namespace std; int** path; int** result; int** square; int dirx[8] = { 0,0,1,1,1,-1,-1,-1 };//8个方向变量 int diry[8] = { 1,-1,-1,0,1,-1,0,1 }; int turn(999); int level(0); int finalLevel(0); int* dir;//步向 int m, n;//迷宫大小 int p, q, r, s;//罗密哦朱丽叶坐标 bool trackback(int p, int q); bool IsFull(); void main() { cout << "输入迷宫大小:" << endl; cin >> m >> n; cout << "输入罗密欧与朱丽叶坐标:" << endl; cin >> p >> q >> r >> s; //记录 result = new int* [2]; result[0]=new int[n * m]; result[1] = new int[n * m]; path = new int* [2]; path[0] = new int[n * m]; path[1] = new int[n * m]; //记录每一步的方向 dir = new int[m * n]; //储存迷宫 square = new int* [m + 2]; for (int i = 0;i < m + 2;i++) { square[i] = new int[n + 2]; } for (int i = 0;i < m + 2;i++) { for (int j = 0;j < n + 2;j++) square[i][j] = 0; } int k,x,y; cout << "输入封闭房间个数:" << endl; cin >> k; cout << "输入封闭房间的坐标;" << endl; for (int i = 0;i < k;i++) { cin >> x >> y; square[x][y] = -1; } for (int i = 0, j = 0;i < m + 2;i++) { square[i][j] = 1; } for (int i = 0, j = 0;j < n + 2;j++) { square[i][j] = 1; } for (int i = 0, j = n + 1;i<m+2;i++) { square[i][j] = 1; } for (int i = m + 1, j = 0;j < n + 2;j++) { square[i][j] = 1; } dir[0] = -1; trackback(p, q); cout << turn - 1 << endl; int i; for (i = 0;i < finalLevel;i++) { square[result[0][i]][result[1][i]] = i + 1; } for (i = 1;i < m + 1;i++) { for (int j = 1; j < n + 1;j++) { cout << square[i][j] << " "; } cout << endl; } } bool trackback(int p, int q) { path[0][level]=p; path[1][level] = q; level++; square[p][q] = 1; if (p==r&&q==s){ if (IsFull()) { int count(0); for (int i = 1;i < level;i++) { if (dir[i] != dir[i - 1]) { count++; } if (count < turn) { finalLevel = level; turn = count; for (int i = 0;i < level;i++) { result[0][i] = path[0][i]; result[1][i] = path[1][i]; } } } } square[p][q] = 0; level--; return false; } for (int i = 0;i < 8;i++) { int x, y; x = p + dirx[i]; y = q + diry[i]; if (square[x][y]==0) { dir[level] = i; trackback(x, y); } } square[p][q] = 0; level--; return true; } bool IsFull() { for (int i = 1;i <= m;i++) { for (int j = 1;j <= n;j++) { if (square[i][j] == 0) { return false; } else { return true; } } } }
trackback:
不完善,会出现无法便利的状况,我明明设计了isfull函数
以上是关于算法————回溯法--迷宫问题(残缺)的主要内容,如果未能解决你的问题,请参考以下文章