原来自己写的代码,结果是3246,翻了题解感觉自己大逻辑上基本没有什么错误,于是就一段段把题解上的代码带入,排查了好久然后发现是tn变量的问题
#include <iostream>
using namespace std;
int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
int ans = 0;
int st[20][20];
void dfs(int x, int y, int n)
{
if (n == 15)
{
ans++;
return;
}
for (int i = 0; i < 4; i++)
{
int tx = x + dx[i];
int ty = y + dy[i];
if (tx < 4 && ty < 4 && tx >= 0 && ty >= 0 && st[tx][ty] == 0)
{
int tn = ++n;//发现是由于这里改变了原来n的值 导致回溯时n的值变化
st[tx][ty] = 1;
dfs(tx, ty, tn);
st[tx][ty] = 0;
}
}
}
int main()
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
st[i][j] = 1;
dfs(i, j, 0);
st[i][j] = 0;
}
}
cout << ans;
return 0;
}
修改后答案是552
#include <iostream>
using namespace std;
int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
int ans = 0;
int st[20][20];
void dfs(int x, int y, int n)
{
if (n == 15)
{
ans++;
return;
}
for (int i = 0; i < 4; i++)
{
int tx = x + dx[i];
int ty = y + dy[i];
if (tx < 4 && ty < 4 && tx >= 0 && ty >= 0 && st[tx][ty] == 0)
{
st[tx][ty] = 1;
dfs(tx, ty, n+1);
st[tx][ty] = 0;
}
}
}
int main()
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
st[i][j] = 1;
dfs(i, j, 0);
st[i][j] = 0;
}
}
cout << ans;
return 0;
}