题目:
题目分析,题目给人的感觉就是深度搜索,找出所有的路径,但是条件(6)使这个标记已找到的路径与标准的深搜不一样,只需要标记当前路径的即可:
#include <Stack>
#include <iostream>
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
int m;
int num;
int targetPos;
int firstPos;
std::cout << "Input :" << std::endl;
std::cin >> n >> m;
for(int i = 0; i < n*m ; i++)
{
int tt;
std::cin >> tt;
if (tt == 1)
firstPos = i;
if (tt == 2)
targetPos = i;
}
std::cin >> num;
int allNum = 0;
int vv[1000] = {0};
std::stack<std::pair<int, int>> nodestack;
std::stack<std::pair<int, int>> curPath;
nodestack.push(std::make_pair(firstPos, 1));
bool arreve =false;
while (!nodestack.empty())
{
int node = nodestack.top().first;
int depth = nodestack.top().second;
int cc = node/m;
int dd = node%m;
nodestack.pop();
// ----- > t
if (depth > num)
continue;;
// clear the same depth
while(!curPath.empty())
{
if(depth > curPath.top().second)
break;
vv[curPath.top().first] = 0;
if (curPath.top().first == targetPos) // clear the arrave
arreve = false;
curPath.pop();
}
// - neighbour -----------
int ll = std::max(cc-1, 0);
int rr = std::min(cc+2, n);
int uu = std::max(dd-1, 0);
int d = std::min(dd+2, m);
for (int ii=ll; ii< rr;ii++)
{
for(int jj=uu; jj<d;jj++)
{
if (vv[ii*m+jj] != 1)
{
nodestack.push(std::make_pair(ii*m+jj, depth+1));
}
}
}
//
if (node == targetPos)
arreve = true;
if (arreve && depth == num)
allNum += 1;
// add the current path and label
curPath.push(std::make_pair(node, depth));
vv[node] = 1;
}
std::cout << "OutPut :" << std::endl;
std::cout << allNum << std::endl;
return 0;
}
运行结果: