练习深度优先搜索-CSDN博客

48 阅读1分钟

其实深度优先搜索用递归实现也不难,算法这种东西,理解不深,过一段时间就忘了。

BNU Personal Training 2017清明(3) G题

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <climits>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <string>
#include <set>
#include <map>
#include <vector>
#include <list>
using namespace std;
#define LL long long
#define INF 0x7f7f7f7f
const int maxn = 1e2 + 7;
int n, m;
char pic[maxn][maxn];

void dfs(int r, int c) {
	if (r < 0 || r >= n || c < 0 || c >= m)
		return; //越界
	for (int dr = -1; dr <= 1; ++dr)
		for (int dc = -1; dc <= 1; ++dc)
			if ((dr != 0 || dc != 0)
				&& (r + dr >= 0 && r + dr < n && c + dc >= 0 && c + dc < m)
				&& pic[r + dr][c + dc] != 'W') {
				pic[r + dr][c + dc] = 'W';
				dfs(r + dr, c + dc);
			}
}

int main()
{
	while (~scanf("%d%d", &n, &m)) {
		for (int i = 0; i < n; ++i) {
			scanf("%s", pic[i]);
		}
		int cnt = 0;
		for (int i = 0; i < n; ++i)
			for (int j = 0; j < m; ++j)
				if (pic[i][j] != 'W' && pic[i][j] != 'C') {
					cnt++;
					dfs(i, j);
				}
		printf("%d\n", cnt);
	}


	return 0;
}

\

You are mapping a faraway planet using a satellite.
Your satellite has captured an image of the planet’s surface. The photographed section can be
modeled as a grid. Each grid cell is either land, water, or covered by clouds. Clouds mean that the
surface could either be land or water, but we can’t tell.
An island is a set of connected land cells. Two cells are considered connected if they share an edge.
Given the image, determine the minimum number of islands that is consistent with the given
information.
Input
The first line of input contains two space-separated integers n and m (1 ≤ n,m ≤ 50).
Each of the next n lines contains m characters, describing the satellite image. Land cells are
denoted by ‘L’, water cells are denoted by ‘W’, and cells covered by clouds are denoted by ‘C’.
Output
Print, on a single line, a single integer indicating the minimum number of islands that is consistent
with the given grid.
Sample Input 
4 5
CCCCC
CCCCC
CCCCC
CCCCC\

Sample Output

0


Sample Input 
3 2
LW
CC
WL


Sample Output

1

\


2016 Pacific Northwest Region Programming Contest—Division 2 19\

by wjqin