A.POJ_1321
考查DFS的一个循环中递归调用


#include<iostream>
#include<cstring>
using namespace std;
char a[10][10];
int book[10];
int n, k;
int total, m;
void DFS(int cur)
{
if (k == m) {
total++;
return;
}
if (cur >= n)
return;
for (int j = 0; j < n; j++)
if (book[j] == 0 && a[cur][j] == '#'){
book[j] = 1;
m++;
DFS(cur + 1);
book[j] = 0;
m--;
}
DFS(cur + 1);
}
int main()
{
int i;
while ((cin >> n >> k) && n != -1 && k != -1){
total = 0;
m = 0;
for (i = 0; i < n; i++)
cin >> a[i];
memset(book, 0, sizeof(book));
DFS(0);
cout << total << endl;
}
return 0;
}
B.POJ_2251
PS:六个方向的BFS题


#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
char map[35][35][35];
int vis[35][35][35];
int k, n, m, sx, sy, sz, ex, ey, ez;
int to[6][3] = { {1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1} };
struct node{
int x, y, z, step;
};
int check(int x, int y, int z){
if (x < 0 || y < 0 || z < 0 || x >= k || y >= n || z >= m)
return 1;
else if (map[x][y][z] == '#')
return 1;
else if (vis[x][y][z])
return 1;
return 0;
}
int bfs(){
int i;
node a, next;
queue<node> Q;
a.x = sx, a.y = sy, a.z = sz;
a.step = 0;
vis[sx][sy][sz] = 1;
Q.push(a);
while (!Q.empty()){
a = Q.front();
Q.pop();
if (a.x == ex && a.y == ey && a.z == ez)
return a.step;
for (i = 0; i < 6; i++){
cout << "a";
cout << a.x << a.y << a.z << endl;
next = a;
next.x = a.x + to[i][0];
next.y = a.y + to[i][1];
next.z = a.z + to[i][2];
cout << "next";
cout << next.x << next.y << next.z << endl;
if (check(next.x, next.y, next.z))
continue;
cout << "标记next";
cout << next.x << next.y << next.z << endl;
vis[next.x][next.y][next.z] = 1;
next.step = a.step + 1;
Q.push(next);
}
}
return 0;
}
int main(){
int i, j, r;
while (cin >> k >> n >> m, n + m + k){
for (i = 0; i < k; i++){
for (j = 0; j < n; j++){
cin >> map[i][j];
for (r = 0; r < m; r++){
if (map[i][j][r] == 'S'){
sx = i, sy = j, sz = r;
}
else if (map[i][j][r] == 'E'){
ex = i, ey = j, ez = r;
}
}
}
}
memset(vis, 0, sizeof(vis));
int ans;
ans = bfs();
if (ans)
cout << "Escaped in " << ans << " minute(s)." << endl;
else
cout << "Trapped!" << endl;
}
return 0;
}