Red and Black (POJ 1979,深度优先搜索)
2017-11-02 10:13
337 查看
题目链接
这道题和前面的例题Lake Couting十分相似。只需判断四个方向上是否为'.',若为'.',移动过去并将这个'.'改为'#',移动的次数加一即为答案。本题比较简单,就不多说了。
#include <cstdio>
const int MAX_W = 20;
const int MAX_H = 20;
int W, H;
char t[MAX_W][MAX_H];
int dx[4] = {-1,1,0,0};
int dy[4] = {0,0,1,-1};
int res;
void dfs(int i,int j) //对四个方向判断,若为'.',移动,计数器+1,并将'.'改为'#'
{
for(int k=0; k<4; k++){
int y = i+dx[k];
int x = j+dy[k];
if(0<=x && x<W && 0<=y && y<H && t[y][x] == '.'){
res++;
t[y][x] = '#';
dfs(i+dx[k], j+dy[k]);
}
}
return ;
}
int main()
{
while(scanf("%d%d", &W, &H)==2 && W!=0){
res = 1;
for(int i=0; i<H; i++){
for(int j=0; j<W; j++){
scanf(" %c", &t[i][j]);
}
}
for(int i=0; i<H; i++){
for(int j=0; j<W; j++){
if(t[i][j] == '@'){
dfs(i, j);
break;
}
}
}
printf("%d\n",res);
}
return 0;
}
这道题和前面的例题Lake Couting十分相似。只需判断四个方向上是否为'.',若为'.',移动过去并将这个'.'改为'#',移动的次数加一即为答案。本题比较简单,就不多说了。
#include <cstdio>
const int MAX_W = 20;
const int MAX_H = 20;
int W, H;
char t[MAX_W][MAX_H];
int dx[4] = {-1,1,0,0};
int dy[4] = {0,0,1,-1};
int res;
void dfs(int i,int j) //对四个方向判断,若为'.',移动,计数器+1,并将'.'改为'#'
{
for(int k=0; k<4; k++){
int y = i+dx[k];
int x = j+dy[k];
if(0<=x && x<W && 0<=y && y<H && t[y][x] == '.'){
res++;
t[y][x] = '#';
dfs(i+dx[k], j+dy[k]);
}
}
return ;
}
int main()
{
while(scanf("%d%d", &W, &H)==2 && W!=0){
res = 1;
for(int i=0; i<H; i++){
for(int j=0; j<W; j++){
scanf(" %c", &t[i][j]);
}
}
for(int i=0; i<H; i++){
for(int j=0; j<W; j++){
if(t[i][j] == '@'){
dfs(i, j);
break;
}
}
}
printf("%d\n",res);
}
return 0;
}
相关文章推荐
- 深度优先搜索(DFS):POJ1979--Red and Black
- POJ 1979 Red and Black【深度优先搜索】
- poj 1979 &&hdu 1312Red and Black (bfs)
- POJ 1979 Red and Black (简单dfs)
- POJ 1979:Red and Black(dfs)
- Red and Black POJ - 1979-入门dfs
- [dfs]poj1979 Red and Black
- POJ-1979&&HDU-1312--Red and Black---DFS深搜
- POJ 1979 Red and Black
- POJ 1979 Red and Black(DFS)
- poj1979——Red and Black
- POJ 1979 Red and Black
- Red and Black POJ - 1979
- poj 1979 Red and Black
- poj 1979 Red and Black (简单裸搜索)
- POJ 1979 Red and Black
- POJ:1979 Red and Black
- POJ-1979 Red and Black
- poj 1979 Red and Black -dfs,回溯
- POJ1979-Red and Black