DFS:Red and Black(POJ 1979)

时间:2022-04-19 11:16:56

               DFS:Red and Black(POJ 1979)

                红与黑

   题目大意:一个人在一个矩形的房子里,可以走黑色区域,不可以走红色区域,从某一个点出发,他最多能走到多少个房间?

   不多说,DFS深搜即可,水题

   注意一下不要把行和列搞错就好了,我就是那样弄错过一次哈哈哈哈

   

 #include <stdio.h>
#include <stdlib.h>
#define MAX_N 20 static int dp[MAX_N][MAX_N];
static int startx;
static int starty;
static int ans; void DFS_Search(const int, const int, const int, const int); int main(void)
{
int W, H, i, j;
while (~scanf("%d%d", &W, &H))
{
if (W == && H == )
break;
ans = ;//先算起点的
for (i = ; i < H; i++)//Read Map
{
getchar();
for (j = ; j < W; j++)
{
scanf("%c", &dp[i][j]);
if (dp[i][j] == '@'){
startx = i; starty = j;
}
}
}
DFS_Search(startx, starty, W, H);
printf("%d\n", ans);
} return ;
} void DFS_Search(const int x, const int y, const int W, const int H)
{
dp[x][y] = '#';
ans++;
if (x - >= && dp[x - ][y] != '#')
DFS_Search(x - , y, W, H);
if (x + < H && dp[x + ][y] != '#')
DFS_Search(x + , y, W, H);
if (y - >= && dp[x][y - ] != '#')
DFS_Search(x, y - , W, H);
if (y + < W && dp[x][y + ] != '#')
DFS_Search(x, y + , W, H);
}