Red and Black POJ - 1979
Red and Black POJ - 1979
There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can’t move on red tiles, he can move only on black tiles.
Write a program to count the number of black tiles which he can reach by repeating the moves described above.
题目大意说的是给你一个初始点@(算作黑色),可以往四个方向走,只能走*(黑色),不能走#(红色),问你最后可以可以走的黑色的总和
联通块问题:
我们只要从输入的时候记下起始点的位置,然后模拟,往四个方向走,#可以不走了,是*就继续走,递归返回步数
处理一下细节问题,把走过的格子标记一下,不能走回头路,最后递归返回的就是最后的总数
同时注意是否越界
代码
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define pi acos(-1)
const int inf = 0x3f3f3f3f;
int dir[4][2]={{0,1},{0,-1},{-1,0},{1,0}};
char s[25][25];
int vis[25][25];
int w,h;
int sx,sy;
int DFS(int i,int j){
int cnt=1;
vis[i][j]=1;
for(int k=0;k<4;k++){
int x=i+dir[k][0];
int y=j+dir[k][1];
if(vis[x][y]||s[x][y]=='#'){
continue;
}
if(x<h&&x>=0&&y>=0&&y<w){
cnt+=DFS(x,y);
}
}
return cnt;
}
int main()
{
while(~scanf("%d%d",&w,&h)&&w&&h){
sx=-1,sy=-1;
memset(vis,0,sizeof(vis));
for(int i=0;i<h;i++){
scanf("%s",s[i]);
if(sx==-1){
for(int j=0;j<w;j++){
if(s[i][j]=='@'){
sx=i;
sy=j;
}
}
}
}
printf("%d\n",DFS(sx,sy));
}
return 0;
}