您的位置:首页 > 其它

POJ 2488 A Knight's Journey

2016-05-18 12:39 295 查看

POJ 2488 A Knight’s Journey

[★★☆☆☆]搜索 深度优先

题目大意:

给出一个国际棋盘的大小,判断马能否不重复的走过所有格,并记录下其中按字典序排列的第一种路径。

样例

输入:

3

1 1

2 3

4 3

输出:

Scenario #1:

A1

Scenario #2:

impossible

Scenario #3:

A1B3C1A2B4C2A3B1C3A4B2C4

解题思路:

水题,根据字典序dfs就行了。

代码

#include <iostream>
#include <algorithm>

using namespace std;

int h, l;
bool used[30][30];

struct point{
int x, y;
};
point ps[30];
int ctp;

int dfs(int x, int y) {
if (x-2 >= 1 && y-1 >= 1 && !used[x-2][y-1]) {
used[x-2][y-1] = 1;
point tp = {x-2, y-1};
ps[ctp++] = tp;
if(dfs(x-2, y-1)) return 1;
ctp--;
used[x-2][y-1] = 0;
}
if (x-2 >= 1 && y+1 <= l && !used[x-2][y+1]) {
used[x-2][y+1] = 1;
point tp = {x-2, y+1};
ps[ctp++] = tp;
if(dfs(x-2, y+1)) return 1;
ctp--;
used[x-2][y+1] = 0;
}
if (x-1 >= 1 && y-2 >= 1 && !used[x-1][y-2]) {
used[x-1][y-2] = 1;
point tp = {x-1, y-2};
ps[ctp++] = tp;
if(dfs(x-1, y-2)) return 1;
ctp--;
used[x-1][y-2] = 0;
}
if (x-1 >= 1 && y+2 <= l && !used[x-1][y+2]) {
used[x-1][y+2] = 1;
point tp = {x-1, y+2};
ps[ctp++] = tp;
if(dfs(x-1, y+2)) return 1;
ctp--;
used[x-1][y+2] = 0;
}
if (x+1 <= h && y-2 >= 1 && !used[x+1][y-2]) {
used[x+1][y-2] = 1;
point tp = {x+1, y-2};
ps[ctp++] = tp;
if(dfs(x+1, y-2)) return 1;
ctp--;
used[x+1][y-2] = 0;
}
if (x+1 <= h && y+2 <= l && !used[x+1][y+2]) {
used[x+1][y+2] = 1;
point tp = {x+1, y+2};
ps[ctp++] = tp;
if(dfs(x+1, y+2)) return 1;
ctp--;
used[x+1][y+2] = 0;
}
if (x+2 <= h && y-1 >= 1 && !used[x+2][y-1]) {
used[x+2][y-1] = 1;
point tp = {x+2, y-1};
ps[ctp++] = tp;
if(dfs(x+2, y-1)) return 1;
ctp--;
used[x+2][y-1] = 0;
}
if (x+2 <= h && y+1 <= l && !used[x+2][y+1]) {
used[x+2][y+1] = 1;
point tp = {x+2, y+1};
ps[ctp++] = tp;
if (dfs(x+2, y+1)) return 1;
ctp--;
used[x+2][y+1] = 0;
}
if (ctp == l*h) {
for (int i = 0; i < ctp; i+
af4d
+) {
char c = ps[i].x + 'A' - 1;
int d = ps[i].y;
cout << c << d;
}
cout << endl;
return 1;
}
return 0;
}

int main() {
int TT;
int ct = 1;
cin >> TT;
while (TT--) {
cin >> l >> h;
ctp = 0;
for (int i = 0; i < 30; i++) {
for (int j = 0; j < 30; j++) {
used[i][j] = 0;
}
}
used[1][1] = 1;
point tp = {1,1};
ps[ctp++] = tp;
cout << "Scenario #" << ct++ << ":" << endl;
if(!dfs(1, 1)) cout << "impossible" << endl;
cout << endl;

}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj