开全局变量写法
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=10;
int m,n,x,y,res;
bool st[N][N];
int dirs[8][2] = {{-2,-1},{-2,1},{-1,2},{1,2},{2,-1},{2,1},{-1,-2},{1,-2}};
int dfs(int x,int y,int cnt)
{
st[x][y] = true;
if(cnt==0) res++;
for(int i=0;i<8;i++)
{
int nx=x+dirs[i][0],ny=y+dirs[i][1];
if(nx<0 || nx>=m || ny<0 || ny>=n || st[nx][ny]) continue;
dfs(nx,ny,cnt-1);
}
st[x][y] = false;
}
int main()
{
int T;
cin >> T;
while(T--)
{
memset(st,0,sizeof st);
res = 0;
cin >> m >> n >> x >> y;
dfs(x,y,m*n-1);
cout << res << endl;
}
return 0;
}
求和写法
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=10;
int m,n,x,y;//,res;
bool st[N][N];
int dirs[8][2] = {{-2,-1},{-2,1},{-1,2},{1,2},{2,-1},{2,1},{-1,-2},{1,-2}};
int dfs(int x,int y,int cnt)
{
if(cnt==0) return 1;//要在st[x][y]=true 前return 否则会导致st[x][y]不再被false
st[x][y] = true;
int res = 0;
for(int i=0;i<8;i++)
{
int nx=x+dirs[i][0],ny=y+dirs[i][1];
if(nx<0 || nx>=m || ny<0 || ny>=n || st[nx][ny]) continue;
res+=dfs(nx,ny,cnt-1);
}
st[x][y] = false;
return res;
}
int main()
{
int T;
cin >> T;
while(T--)
{
memset(st,0,sizeof st);
cin >> m >> n >> x >> y;
cout << dfs(x,y,m*n-1) << endl;
}
return 0;
}