A.POJ_1321
考查DFS的一个循环中递归调用
#include<iostream>
#include<cstring>
using namespace std;
char a[10][10]; //记录棋盘位置
int book[10]; //记录一列是否已经放过棋子
int n, k; // k 为 需要放入的棋子数
int total, m; //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>
//bfs对于每一层的搜索都是很详细的可以扫完所有
using namespace std;
char map[35][35][35]; // 用于建图
int vis[35][35][35]; // 查询数组 判断该点是否被访问了
int k, n, m, sx, sy, sz, ex, ey, ez; //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; // x,y,z 表示 node 声明出来的点的 三个坐标的值 和 该点下的是第几步
};
int check(int x, int y, int z){
// 若 1.越界 2.是障碍物 3.查询过 该函数的返回值是 1 否则 则是 0;
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()){ // 如果队列q为空就证明没找到可以通过的路径
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){ // k为牢房个数n,m代表n行m列
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;
}