求算法或源程序(C或C++)

来源:百度知道 编辑:UC知道 时间:2024/05/09 15:24:49
问题描述:
在4*4的网格中共有14个位置(分布的大概位置如下图)
1 5 9
2 6 10 13
3 7 11 14
4 8 12
要求在这十四个位置中任意选个初始位置,经过一定的路径还要回到初始位置。
行走路径的约束条件:(S.T)
(1) 行走路线必须是‘日’子型;即如果选的初始位置为5,则下一步只能走
3,11,13中的一个位置。如果初始位置为1,则下一步只能走7,10中的一个位置
(2) 已经走过的位置不能再走(除初始位置以外)

例如:初始位置选择2,可以
2 8 14 6 4 11 5 13 12 3 10 1 7 9 2(一个排列)
回到初始位置

要求算出所以可能的路径(排列)
谢谢江湖少侠:
你写的源程序我有写地方不懂(是我自己对类不懂),可我在VC++ 6.0 上试了编译可以通过,可连接出错。也就无法验证答案了,
还希望你能用自然语言描述下算法,尤其是怎样实现只走‘日’字和怎样让他不再回到已经走过的位置上的

我只想把它搞明白,分还可以再加

有链接错误吗?我这里也是使用vc6.0,很正常啊,下面加了些注释,以解楼主的疑问。

#include <iostream>
#include <vector>
using namespace std;

class FindPath{
public:
FindPath()
{
m_paths.clear();
}
public:
void getPaths(int startpos);
void putout();

private:
inline bool isvalidpath(vector<pair<int, int> > path, int i, int j, int startpos);
inline void pushPath(vector<pair<int, int> > path);
void findPaths(vector<pair<int, int> > path, int i, int j, int startpos);

private:
const static int webs[4][4]; //网格
vector<vector<int> > m_paths; //保存所有的路径集
};

const int FindPath::webs[4][4] = { {1, 5, 9, 0},
{2, 6, 10, 13},
{3, 7, 11, 14},
{4, 8, 12, 0}
};

inline void FindPath::pushPath(vector<pair<int, int> > path) //将获得的路径集保存到m_paths中
{
vector<int&