1.acwing 1114.棋盘问题
传送门
- 题目大意:给你一个n * n的矩阵,其中里面包含两种字符’#‘和’.’,’#‘表示是棋盘,即可以放棋子,‘.’表示是空白区域不可以放棋子,现在给你k个棋子,要求每一行,每一列上不能有两颗棋子,问棋子有多少种摆放的可能
- 思路:直接使用dfs进行爆搜即可
- 代码如下
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int N = 10;
char g[N][N];
bool line[N];//因为每次直接处理下一行,所以只需要标记列即可
int n, k, m;
int res;
void dfs(int x)//按行进行摆放然后爆搜
{
if (m == k)
{
res ++;
return ;
}
else if (x == n) return ;
for (int i = 0; i < n; i ++)
if (!line[i] && g[x][i] == '#')
{
line[i] = true;//进行摆放
m ++;
dfs(x + 1);
m --;
line[i] = false;//恢复现场
}
dfs(x + 1);//此行也可以不放棋子
}
int main()
{
while (scanf("%d%d", &n, &k) || ( n != -1 && k != -1))
{
for (int i = 0; i < n; i ++) cin >> g[i];
res = 0;
m = 0;
memset(line, false, sizeof(line));
dfs(0);
printf("%d\n", res);
}
return 0;
}
2.地牢大师
题目链接
- 思路:这是每次移动权重都为1的图,要求算出最短路,使用bfs即可,需要注意的是,这个图是三维图形,需要一个三维数组来存储,同时因为终点为’E’,判断是否可以走的条件就应该是用’#'来判断,这里我debug了好久,其它都是模板。
- ac代码如下:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int dx[6] = {-1, 1, 0, 0, 0, 0}, dy[6] = {0, 0, -1, 1, 0, 0}, dz[6] = {0, 0, 0, 0, -1, 1};
const int N = 110;
char g[N][N][N];
int res[N][N][N];
int l, r, c;
struct node
{
int z, x, y;
}st, ed;
void bfs()
{
queue<node> q;
q.push(st);
res[st.z][st.x][st.y] = 0;
while (q.size())
{
auto t = q.front();
q.pop();
for (int i = 0; i < 6; i ++)
{
int z = t.z + dz[i], y = t.y + dy[i], x = t.x + dx[i];
if (x >= 0 && x < r && y >= 0 && y < c && z >= 0 && z < l && res[z][x][y] == -1 && g[z][x][y] != '#')
{
q.push({z, x, y});
res[z][x][y] = res[t.z][t.x][t.y] + 1;
if (z == ed.z && y == ed.y && x == ed.x) return ;
}
}
}
}
int main()
{
while (scanf("%d%d%d", &l, &r, &c) && l)
{
memset(res, -1, sizeof(res));
for (int i = 0; i < l; i ++)
for (int j = 0; j < r; j ++)
{
for (int k = 0; k < c; k ++)
{
cin >> g[i][j][k];
if (g[i][j][k] == 'S') st = {i, j, k};
else if(g[i][j][k] == 'E') ed = {i, j, k};
}
while (getchar() == ' ') ;
}
bfs();
int ans = res[ed.z][ed.x][ed.y];
if (ans == -1) printf("Trapped!\n");
else printf("Escaped in %d minute(s).\n", ans);
}
return 0;
}
3.抓住那头牛
题目链接
- 简单的bfs,代码如下
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1e5 + 10;
int res[N];
int n, k;
int bfs()
{
queue<int> q;
q.push(n);
res[n] = 0;
while (q.size())
{
int t = q.front();
q.pop();
int a = 2 * t, b = t + 1, c = t - 1;
if (a >= 0 && a <= 1e5 && res[a] == -1)
{
q.push(a);
res[a] = res[t] + 1;
}
if(b >= 0 && b <= 1e5 && res[b] == -1)
{
q.push(b);
res[b] = res[t] + 1;
}
if(c >= 0 && c <= 1e5 && res[c] == -1)
{
q.push(c);
res[c] = res[t] + 1;
}
//cout << res[t] << endl;
if (res[k] != -1) break;
}
return res[k];
}
int main()
{
scanf("%d%d", &n, &k);
memset(res, -1, sizeof(res));
cout << bfs() << endl;
return 0;
}