poj 2488
2018-03-15 14:28
246 查看
这题比较水,写博客是为了纪念下终于找到一个符合自己风格的深搜写法:所有状态的变化都放在深搜函数首部,状态恢复都放在尾部。#include <iostream>
#include <cstring>
#include <vector>
#include <cstdio>
using namespace std;
int dir[8][2] = {{-1, -2}, {1, -2}, {-2, -1}, {2, -1},
{-2, 1}, {2, 1}, {-1, 2}, {1, 2}};
int vis[30][30];
pair <int, int> a[1000];
int p, q;
int flag;
bool judge(int x, int y){
return (0 < x && x <= p && 0 < y && y <= q);
}
void dfs(int x, int y, int cnt){
if(flag)
return ;
vis[x][y] = 1;
a[cnt]. first = x, a[cnt]. second = y;
if(cnt == p * q ){
flag = 1;
for(int i = 1; i <= cnt; i ++)
cout << char(a[i]. second - 1 + 'A') << a[i]. first;
cout << endl;
cout << endl;
return ;
}
for(int i = 0; i < 8; i ++){
int nx = x + dir[i][0], ny = y + dir[i][1];
if(judge(nx, ny) && ! vis[nx][ny]){
dfs(nx, ny, cnt + 1);
}
}
vis[x][y] = 0;
return ;
}
int main(){
int T;
cin >> T;
for(int t = 1; t <= T; t ++){
flag = 0;
memset(a, 0, sizeof(a));
memset(vis, 0, sizeof(vis));
cin >> p >> q;
printf("Scenario #%d:\n", t);
dfs(1, 1, 1);
if(! flag){
cout << "impossible" << endl << endl;
continue;
}
}
return 0;
}
#include <cstring>
#include <vector>
#include <cstdio>
using namespace std;
int dir[8][2] = {{-1, -2}, {1, -2}, {-2, -1}, {2, -1},
{-2, 1}, {2, 1}, {-1, 2}, {1, 2}};
int vis[30][30];
pair <int, int> a[1000];
int p, q;
int flag;
bool judge(int x, int y){
return (0 < x && x <= p && 0 < y && y <= q);
}
void dfs(int x, int y, int cnt){
if(flag)
return ;
vis[x][y] = 1;
a[cnt]. first = x, a[cnt]. second = y;
if(cnt == p * q ){
flag = 1;
for(int i = 1; i <= cnt; i ++)
cout << char(a[i]. second - 1 + 'A') << a[i]. first;
cout << endl;
cout << endl;
return ;
}
for(int i = 0; i < 8; i ++){
int nx = x + dir[i][0], ny = y + dir[i][1];
if(judge(nx, ny) && ! vis[nx][ny]){
dfs(nx, ny, cnt + 1);
}
}
vis[x][y] = 0;
return ;
}
int main(){
int T;
cin >> T;
for(int t = 1; t <= T; t ++){
flag = 0;
memset(a, 0, sizeof(a));
memset(vis, 0, sizeof(vis));
cin >> p >> q;
printf("Scenario #%d:\n", t);
dfs(1, 1, 1);
if(! flag){
cout << "impossible" << endl << endl;
continue;
}
}
return 0;
}
相关文章推荐
- POJ-2488-A Knight's Journey
- POJ 2488 A Knight's Journey
- 【POJ 2488】A Knight's Journey
- POJ_2488: A Knight's Journey
- POJ 2488 DFS+回溯
- POJ 2488 A Knight's Journey
- POJ 2488 A Knight's Journey
- POJ-2488 A Knight's Journey 解题报告
- poj 2488 A Knight's Journey
- poj 2488 A Knight's Journey(dfs)
- poj 2488
- POJ 2488:A Knight's Journey
- POJ 2488 A Knight's Journey
- POJ 2488 A Knight's Journey
- POJ 2488 A Knight's Journey【dfs过】
- POJ 2488 Children of the Candy Corn (搜索)
- DFS poj 2488
- POJ 2488 A Knight's Journey
- poj 2488
- Poj(2488),按照字典序深搜