2018-7-11 ACM 专项刷题 dfs + bfs

1. 递归:

先说一个递归的含义,就是在某个函数内部调用这个函数本身,或者说,调用一个与该函数完全相同的函数。

最简单的一个递归的应用就是,辗转相除法求最大公约数Gcd:

LL gcd(LL x, LL y) {
    if(x % y == 0) return y;
    else return gcd(y, x % y);
}

 

2. dfs(深度优先搜索):

dfs 也有几个很常见的应用,基础思想也是递归,下面简单说下常见的dfs应用:

(1)八皇后问题 & N皇后问题:

对应题目:HDU - 2553

八皇后问题,就是在8 * 8的棋盘上摆放八个皇后,要求这八个皇后,不同行,不同列,不同对角线, 问多少种摆法。

代码如下:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
#define N 8 //八皇后
int ans;
int col[10]; //col[i]表示, 第i行的皇后放在第col[i]列

void dfs(int k) {
    if(k == N) ans++;
    else {
        for(int i = 0; i < N; i++) {
            bool flg = 1;
            col[k] = i;
            for(int j = 0; j < k; j++) { //判断第k行的皇后与第j行的皇后是否在同一列, 是否在同一对角线
                if(col[k] == col[j] || k - col[k] == j - col[j] || k + col[k] == j + col[j]) {
                    flg = 0; //同一主对角线上的元素的(行 - 列)是一个常数, 同一副对角线上的元素的(行 + 列)是一个常数
                    break;
                }
            }
            if(flg) dfs(k + 1);
        }
    }
}
int main() {
    dfs(0);
    printf("%d\n", ans);
} 

接下来是N皇后,开一个全局的N即可,传入一个N,为了防止超时,可以打表,代码如下:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
int col[13];
int N;

/*void dfs(int k) {
	if(k == N) ans++;
	else {
		for(int i = 0; i < N; i++) {
			bool flg = 1;
			col[k] = i;
			for(int j = 0; j < k; j++) {
				if(col[k] == col[j] || k - col[k] == j - col[j] || k + col[k] == j + col[j]) {
					flg = 0;
					break;
				}
			}
			if(flg) dfs(k + 1);
		}
	}
}*/

int ans[11] = {-1, 1, 0, 0, 2, 10, 4, 40, 92, 352, 724};

int main() {
	while(~scanf("%d", &N) && N) {
		//ans = 0;
		//dfs(0);
		printf("%d\n", ans[N]);
	}
}

所谓打表,就是将 dfs 跑出的 1 ~ 10 皇后的结果存进ans数组,在输出ans[N]即可。

(2)全排列问题:

对应题目:HDU - 1716

先说下 1 ~ N 的全排列(字典序升序),代码如下:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
int n;
bool vis[10];
int ans[10];

void Dfs(int x) {
	if(x == n + 1) {
		for(int i = 1; i <= n; i++) printf("%d ", ans[i]);
		printf("\n");
	}
	for(int i = 1; i <= n; i++) {
		if(!vis[i]) {
			vis[i] = 1;
			ans[x] = i;
			Dfs(x + 1);
			vis[i] = 0;
		}
	}
}

int main() {
	scanf("%d", &n);
	Dfs(1);
	return 0;
}

下面仿照上面的思路,写一下传进任意四个数,所能形成的四位数的全排列(以字典序升序),代码如下:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxx = 1e5 + 7;
bool vis[10];
int ans[10];
int t[10];
int n;
bool chk[maxx];
int res[maxx];
int p;

void Dfs(int x) {
	if(x == 5) {
		int tmp = 0;
		for(int i = 1; i <= 4; i++) {
			tmp += ans[i] * pow(10, 4 - i);
		}
		if(!chk[tmp] && tmp >= 1000) {
			p++;
			res[p] = tmp;
			chk[tmp] = 1;
		}
	}
	for(int i = 1; i <= 4; i++) {
		if(!vis[i]) {
			vis[i] = 1;
			ans[x] = t[i];
			Dfs(x + 1);
			vis[i] = 0;
		}
	}
}

int main() {
	bool flg = 0;
	int cnt = -1;
	while(scanf("%d %d %d %d", &t[1], &t[2], &t[3], &t[4]) != EOF) {
		if(t[1] == 0 && t[2] == 0 && t[3] == 0 && t[4] == 0) break;
		memset(chk, 0, sizeof(chk));
		memset(vis, 0, sizeof(vis));
		memset(res, 0, sizeof(res));
		p = 0;
		sort(t + 1, t + 5);
		Dfs(1);
		for(int i = 1; i <= p; i++) printf("%d\n", res[i]);
	}
}

(3)连通及连通块问题:

对应题目:HDU - 1312 、HDU - 1241 、Codeforces - 377A 、POJ - 2386

HDU - 1312 题解:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int n, m, ans;
char str[25][25];
int dx[5] = {-1, 0, 1, 0};
int dy[5] = {0, -1, 0, 1};

void dfs(int x, int y) {
	if(x < 1 || x > n || y < 1 || y > m) return;
	if(str[x][y] != '.') return;
	ans++;
	str[x][y] = '#';
	for(int i = 0; i < 4; i++) {
		int xx = x + dx[i];
		int yy = y + dy[i];
		dfs(xx, yy);
	}
}

int main() {
	while(~scanf("%d %d", &m, &n)) {
		if(n == 0 && m == 0) break;
		int x, y;
		ans = 0;
		for(int i = 1; i <= n; i++) {
			for(int j = 1; j <= m; j++) scanf(" %c", &str[i][j]);
		}
		for(int i = 1; i <= n; i++) {
			for(int j = 1; j <= m; j++) {
				if(str[i][j] == '@') x = i, y = j;
			}
		}
		str[x][y] = '.';
		dfs(x, y);
		printf("%d\n", ans);
	}
	return 0;
}

HDU - 1241 题解:

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
int n, m;
char s[110][110];

void dfs(int x, int y) {
	if(x < 1 || x > n || y < 1 || y > m) return;
	if(s[x][y] == '*') return;
	s[x][y] = '*';
	for(int i = -1; i <= 1; i++) {
		for(int j = -1; j <= 1; j++) {
			if(i != 0 || j != 0) dfs(x + i, y + j);
		}
	}
}

int main() {
	while(~scanf("%d %d", &n, &m) && n && m) {
		int ans = 0;
		for(int i = 1; i <= n; i++)
			for(int j = 1; j <= m; j++) scanf(" %c", &s[i][j]);
		for(int i = 1; i <= n; i++) {
			for(int j = 1; j <= m; j++) {
				if(s[i][j] == '@') {
					ans++;
					dfs(i, j);
				}
			}
		}
		printf("%d\n", ans);
	}
} 

Codeforces - 377A 题解:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
int h, w, t;
char str[550][550];

void dfs(int x, int y) {
	if(x < 1 || x > h || y < 1 || y > w) return;
	if(str[x][y] != '.') return;
	str[x][y] = '!';
	int num = 0;
	for(int i = -1; i <= 1; i++) {
		for(int j = -1; j <= 1; j++) {
			if(!t) return;
			if(fabs(i) != fabs(j)) {
				dfs(x + i, y + j);
				if(str[x + i][y + j] == '.') num++;
			}
		}
	}
	if(num == 0) {
		str[x][y] = 'X';
		t--;
	}
}

int main() {
	scanf("%d %d %d", &h, &w, &t);
	for(int i = 1; i <= h; i++) {
		for(int j = 1; j <= w; j++) scanf(" %c", &str[i][j]);
	}
	for(int i = 1; i <= h; i++) {
		for(int j = 1; j <= w; j++) {
			dfs(i, j);
		}
	}
	for(int i = 1; i <= h; i++) {
		for(int j = 1; j <= w; j++) {
			if(str[i][j] == '!') str[i][j] = '.';
		}
	}
	for(int i = 1; i <= h; i++) {
		for(int j = 1; j <= w; j++) printf("%c", str[i][j]);
		printf("\n");
	}
	return 0;
} 

POJ - 2386 题解:

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
int n, m;
char str[110][110];

void dfs(int x, int y) {
	if(x < 1 || x > n || y < 1 || y > m) return;
	if(str[x][y] == '.') return;
	str[x][y] = '.';
	for(int i = -1; i <= 1; i++) {
		for(int j = -1; j <= 1; j++) {
			if(i != 0 || j != 0) dfs(x + i, y + j);
		}
	}
}

int main() {
	int p = 0;
	scanf("%d %d", &n, &m);
	for(int i = 1; i <= n; i++)
		for(int j = 1; j <= m; j++) scanf(" %c", &str[i][j]);
	for(int i = 1; i <= n; i++) {
		for(int j = 1; j <= m; j++) {
			if(str[i][j] == 'W') {
				p++;
				dfs(i, j);
			}
		}
	}
	printf("%d\n", p);
	return 0;
}

(4)可转化为深搜的其他应用:

对应题目:Codeforces - 96B

我不会转化为dfs的模型,纯暴力打表过的,我博客写过这题题解,详见链接:

https://blog.csdn.net/ericgipsy/article/details/80164017

3. bfs(广度优先搜索):

(1)最短路问题:

bfs主要应用于求图内某一点到另一点的最短路径,模板代码如下:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxx = 1e5 + 7;
const int Inf = 1 << 30;

char s[55][55];
int vis[55][55];
int dd[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
int n, m;
int ans, res;

struct PP {
    int x, y, flg;
} p, q;

int Bfs(int x, int y) { //返回的是最短路径经过的所有点的个数
    memset(vis, 0, sizeof(vis));
    queue <PP> qua;
    p.x = x, p.y = y, p.flg = 1;
    qua.push(p);
    while(!qua.empty()) {
        q = qua.front();
        qua.pop();
        if(q.x == n && q.y == m) return q.flg;
        if(!vis[q.x][q.y]) {
            vis[q.x][q.y] = 1;
            for(int i = 0; i < 4; i++) {
                int dx = q.x + dd[i][0];
                int dy = q.y + dd[i][1];
                if (dx >= 1 && dx <= n && dy >= 1 && dy <= m && s[dx][dy] != '#' && !vis[dx][dy]) {
                    PP tmp;
                    tmp.x = dx, tmp.y = dy, tmp.flg = q.flg + 1;
                    qua.push(tmp);
                }
            }
        }
    }
    return -1;
}

void Init() {
    scanf("%d %d", &n, &m);
    for(int i = 1; i <= n; i++) scanf("%s", s[i] + 1);
}

int main() {
    Init();
    cout << Bfs(1, 1) << endl;
}

由于bfs对路径是实时更新的,所以无法保存路径,可以借助dfs或者vector保存路径。

对应题目:Atcoder Beginner Contest 088 - D

题解:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxx = 1e5 + 7;
const int Inf = 1 << 30;

char s[55][55];
int vis[55][55];
int dd[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
int n, m;
int ans, res;

struct PP {
	int x, y, flg;
} p, q;

int Bfs(int x, int y) {
	memset(vis, 0, sizeof(vis));
	queue <PP> qua;
	p.x = x, p.y = y, p.flg = 1;
	qua.push(p);
	while(!qua.empty()) {
		q = qua.front();
		qua.pop();
		if(q.x == n && q.y == m) return q.flg;
		if(!vis[q.x][q.y]) {
			vis[q.x][q.y] = 1;
			for(int i = 0; i < 4; i++) {
				int dx = q.x + dd[i][0];
				int dy = q.y + dd[i][1];
				if (dx >= 1 && dx <= n && dy >= 1 && dy <= m && s[dx][dy] != '#' && !vis[dx][dy]) {
					PP tmp;
					tmp.x = dx, tmp.y = dy, tmp.flg = q.flg + 1;
					qua.push(tmp);
				}
			}
		}
	}
	return -1;
}

void Init() {
	scanf("%d %d", &n, &m);
	for(int i = 1; i <= n; i++) scanf("%s", s[i] + 1);
}

int main() {
	Init();
	ans = n * m;
	for(int i = 1; i <= n; i++)
		for(int j = 1; j <= m; j++) if(s[i][j] == '#') ans--;
	if(s[1][1] == '#' || s[n][m] == '#') res = -1;
	else res = Bfs(1, 1);
	if(res == -1) ans = -1;
	else ans -= res;
	cout << ans << endl;
}

(2)可转化为最短路的其他应用:

对应题目:POJ - 3278

POJ - 3278 题解:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <queue>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxx = 1e5 + 7;
int N, K;
bool vis[2 * maxx];

struct PP {
	int ans;
	int dp;
} p, q;

queue <PP> qua;

int Bfs(int n, int k) {
	p.ans = 0, p.dp = n;
	qua.push(p);
	while(!qua.empty()) {
		p = qua.front();
		qua.pop();
		if(p.dp == k) return p.ans;
		if(p.dp < k && !vis[p.dp * 2]) {
			q.dp = p.dp * 2;
			q.ans = p.ans + 1;
			vis[q.dp] = 1;
			qua.push(q);
		}
		if(p.dp < k && !vis[p.dp + 1]) {
			q.dp = p.dp + 1;
			q.ans = p.ans + 1;
			vis[q.dp] = 1;
			qua.push(q);
		}
		if(p.dp - 1 >= 0 && !vis[p.dp - 1]) {
			q.dp = p.dp - 1;
			q.ans = p.ans + 1;
			vis[p.dp] = 1;
			qua.push(q);
		}
	}
}

int main() {
	cin >> N >> K;
	if(N >= K) cout << N - K << endl;
	else cout << Bfs(N, K) << endl;
	return 0;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值