POJ 4123:马走日
代码:
C
#include<stdio.h>
int flag[20][20];//判断是否走过
int n, m, sum;//设置行和列以及结果
int move[10][10] = { {-1, 2},
{1, 2},
{2, 1},
{2, -1},
{1, -2},
{-1, -2},
{-2, -1},
{-2, 1} };//方向
bool compare(int x, int y) {//判断是否存在越界以及走过
if (x >= 0 && x < n && y >= 0 && y < m && flag[x][y] == 0) {
return true;
}
else {
return false;
}
}
void DFS(int x, int y, int step) {//深搜
if (step == n * m) {//遇到走完返回
sum++;
return;
}
int a, b;
for (int i = 0; i <= 7; i++) {
a = x + move[i][0];//给a赋值
b = y + move[i][1];//给b赋值
if (compare(a, b)) {
flag[a][b] = 1;
DFS(a, b, step + 1);
flag[a][b] = 0;
}
}
}
int main() {
int k;
while (scanf("%d",&k)!=EOF){
while (k--) {
int x, y;//起始坐标
sum = 0;//清零
scanf("%d %d %d %d", &n, &m, &x, &y);//赋值
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
flag[i][j] = 0;
}
}//遍历为零
flag[x][y] = 1;//将起始位置设为走过
DFS(x, y, 1);//深搜
printf("%d\n", sum);//输出
}
}
return 0;
}
C++
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <functional>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <algorithm>
#define ll long long
#define ull unsigned long long
#define dd double
#define mes(x, y) memset(x,y,sizeof(x))
using namespace std;
ll hang, lie, sum;
map<pair<ll, ll>, ll> mm;
ll moving[10][10] = {{-1, 2},
{1, 2},
{2, 1},
{2, -1},
{1, -2},
{-1, -2},
{-2, -1},
{-2, 1}};
bool Around(ll x, ll y) {
return (x >= 0 && x < hang && y >= 0 && y < lie);
}
void DFS(ll comingx, ll comingy, ll step) {
if (step == hang * lie) {
sum++;
return;
}
for (ll i = 0; i <= 7; i++) {
pair<ll, ll> st;
st.first = comingx + moving[i][0];
st.second = comingy + moving[i][1];
if (Around(st.first, st.second) && !mm[st]) {
mm[st] = 1;
DFS(st.first, st.second, step + 1);
mm[st] = 0;
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
ll n, k;
while (cin >> n) {
while (n--) {
pair<ll, ll> st;
mm.clear();
cin >> hang >> lie >> st.first >> st.second;
mm[st] = 1;
sum = 0;
DFS(st.first, st.second, 1);
cout << sum << endl;
}
}
}