HDU 1312 Red and Black

题目地址:点击打开链接

题意:一间房子里的地板只有红色的和黑色的,他不能走红色的地板,问从起始点开始他能走多少块黑色的地板,'.' - a black tile ,'#' - a red tile 

'@' - a man on a black tile(appears exactly once in a data set) 

思路:DFS

AC代码:

#include <iostream>

using namespace std;

int m,n,sum;
char map[25][25];
int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
void dfs(int x,int y)
{
    int i,newx,newy;
    map[x][y] = '#';
    sum++;
    for(i=0; i<4; i++)
    {
        newx = x + dir[i][0];
        newy = y + dir[i][1];
        if(newx < n && newx >= 0 && newy < m && newy >= 0 && map[newx][newy] != '#')
        {
            dfs(newx,newy);
        }
    }
}
int main()
{
    int i,j;
    int starti,startj;
    while(cin>>m>>n)
    {
        if(m + n == 0)
            break;
        sum = 0;
        for(i=0; i<n; i++)
        {
            for(j=0; j<m; j++)
            {
                cin>>map[i][j];
                if(map[i][j] == '@')
                {
                    starti = i;
                    startj = j;
                }
            }
        }
        dfs(starti,startj);
        cout<<sum<<endl;
    }
    return 0;
}


你可能感兴趣的:(HDU 1312 Red and Black)