B:[POJ] 2386 — Lake Counting
原题链接:https://vjudge.net/problem/14167/origin
题目大意:
给出N*M的一个地图,’ . ‘代表着没有水的陆地,’ W '代表着水洼,所以相邻的水洼,包括对角相邻,形成一个池塘,要求的就是池塘的数目。
题目分析:
通过深度优先搜索,对每一个水洼进行遍历,被遍历过的水洼被标记为陆地,防止被再次遍历或者进入死循环,每次退出了循环则池塘数目加一,直到地图上没有水洼。
代码实现:
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
char map[105][105];
//对应相邻的八个方位
int neighbor[8][2] = {{-1,-1},{-1,0},{-1,1},{0,-1},
{0,1},{1,-1},{1,0},{1,1}};
int n, m;
void dfs(int x, int y)
{
map[x][y] = '.'; //将遍历过的水洼标记为陆地
int i, x1, y1;
for(i=0; i<8; i++){
x1 = x + neighbor[i][0];
y1 = y + neighbor[i][1];
if(x1 >= 0 && y1 >= 0 &&
x1 < n && y1 < m &&
map[x1][y1] == 'W'){
dfs(x1,y1); //对相邻的水洼进行遍历
}
}
}
int main()
{
int ans = 0;
int i, j;
cin >> n >> m;
getchar();
for(i=0; i<n; i++){
for(j=0; j<m; j++){
cin >> map[i][j];
}
getchar();
}
//对每个水洼进行遍历
for(i=0; i<n; i++){
for(j=0; j<m; j++){
if(map[i][j] == 'W'){
dfs(i,j);
ans++; //退出了循环,数目+1
}
}
}
cout << ans << endl;
}
C:[POJ] 1979 — Red and Black
原题链接:https://vjudge.net/problem/26084/origin
题目大意:
给出W*H的地图,’ . ‘代表着黑瓷砖,’ # ‘代表着红瓷砖,’ @ '代表着人的位置,人的脚下也是黑瓷砖。要求的就是人所能走的最多的黑瓷砖的数目。
题目分析:
通过深度优先搜索,从人的位置开始对相邻的黑瓷砖进行遍历,被遍历过的黑瓷砖被标记为红瓷砖,防止被再次遍历或者进入死循环,同时黑瓷砖的数目加一。做法和上面的基本相同。
代码实现:
#include <iostream>
#include <cstdio>
using namespace std;
int w, h;
int ans = 0;
char _map[21][21];
//对应四个方向
int dir[4][2] = {{0,-1},{0,1},{-1,0},{1,0}};
void dfs(int x, int y)
{
int i;
int x1, y1;
_map[x][y] = '#'; //标记为红
ans++; //黑瓷砖数目+1
for(i=0; i<4; i++){
x1 = x + dir[i][0];
y1 = y + dir[i][1];
if(((0 <= x1 && x1 < h) && (0 <= y1 && y1 <w)) && _map[x1][y1] == '.'){
dfs(x1,y1); //对相邻的黑瓷砖进行遍历
}
}
}
int main()
{
int ai, aj;
int i,j;
cin >> w >> h;
while(w && h)
{
ans = 0;
for(i=0; i<h; i++){
for(j=0; j<w; j++){
cin >> _map[i][j];
if(_map[i][j] == '@'){ //记下人的位置
ai = i;
aj = j;
}
}
}
dfs(ai,aj);
cout << ans << endl;
cin >> w >> h;
}
return 0;
}
最后,希望路过的dl们能给予改进的建议!