#include <bits/stdc++.h>
using namespace std;
int n;
//质数判断
int check(int x)
{
if(x < 2) return 0;
for(int i = 2; i <= x / i; i ++)
{
if(x % i == 0) return 0;
}
return 1;
}
/**
u 即将要选的位置
val 代表当前选择产生的结果
*/
void dfs(int u, int val)
{
if(u == n + 1)
{
cout << val << endl;
}else
{
//填上当前的选择,全排列
for(int i = 1; i <= 9; i ++) //xxx?
{
int p = val * 10 + i;
if(check(p) == 1)
{
dfs(u + 1, p);
}
}
}
}
int main()
{
cin >> n;
dfs(1, 0);
return 0;
}
组合
T760490 月色的组合
思路: 我们先清楚排列与组合的区别,区别在与组合没有重复的,所以会多一个参数k记录上一次的选择,本次循环的范围会缩短到 i = > [k + 1, n]
#include <bits/stdc++.h>
using namespace std;
int a[50];
int n, m;
/**
u 即将要填的位置
k 记录上一次选的数字
*/
void dfs(int u, int k)
{
if(u == m + 1)
{
//打印方案
for(int i = 1; i <= m; i ++)
{
cout << a[i] << " ";
}
cout << endl;
return ;
}else
{
//多种选择
for(int i = k + 1; i <= n; i ++)
{
a[u] = i; //a[u] = i
dfs(u + 1, i);
}
}
}
int main()
{
cin >> n >> m;
dfs(1, 0);
return 0;
}
P2404 自然数的拆分问题
思路:本题与上题类似,区别在于本题是在拆分数字,且输出格式比较麻烦
#include <bits/stdc++.h>
using namespace std;
int a[10];
int n;
/**
u 即将要去填第几个位置
x 要去拆分的数字
k 上一次的选择
*/
void dfs(int u, int x, int k)
{
if(x == 0)
{
if(a[1] == n) return; //跳过自己等于自己
cout << a[1];
for(int i = 2; i < u; i ++)
{
cout << "+" << a[i];
}
cout << endl;
}else{
//每一次放的数字范围
for(int i = k; i <= 8; i ++)
{
if(x - i >= 0)
{
a[u] = i;
dfs(u + 1, x - i, i);
}
}
}
}
int main()
{
cin >> n;
dfs(1, n, 1);
return 0;
}
二维迷宫问题
思路:二维迷宫到达类问题,询问两点之间能否到达
坑点:
1.下标本题从0计数
2.多组数据,标记数组要记得清空
3.起点和终点本身就不能走
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
char a[N][N]; //存储地图
bool st[N][N]; //有没有走过
int n, cnt, t;
int sx, sy, ex, ey; //起点 和 终点
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
void dfs(int x, int y)
{
if(x == ex && y == ey)
{
cnt ++;
}else
{
//选择周围的四个方向
for(int i = 0; i <= 3; i ++)
{
int tx = x + dx[i];
int ty = y + dy[i];
//出界跳过
if(tx < 1 || tx > n || ty < 1 || ty > n) continue;
//能不能走 && 有没有走过
if(a[tx][ty] == '.' && st[tx][ty] == false)
{
st[tx][ty] = true;
dfs(tx, ty);
}
}
}
}
int main()
{
cin >> t;
while(t --)
{
cin >> n;
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= n; j ++)
{
cin >> a[i][j];
}
}
//输入起点和终点
cin >> sx >> sy >> ex >> ey;
sx += 1;
sy += 1;
ex += 1;
ey += 1;
//清空数组与变量的标记
memset(st, 0, sizeof st);
cnt = 0;
//特判起点和终点是否为 # 号(不能走)
if(a[sx][sy] == '#' || a[ex][ey] == '#')
{
cout << "NO" << endl;
continue;
}
//搜索
st[sx][sy] = true;
dfs(sx, sy);
//判断
if(cnt == 0) cout << "NO" << endl;
else cout << "YES" << endl;
}
return 0;
}