hdu1241

oil deposits

本题思路较为简单,依次查找,找到相关元素就压到队列里,利用队列完成其元素周围的所有元素的全部遍历,并进行标记,逐次遍历完。注意存储时的技巧,这样在操作时可以减少好多冗杂的操作。还有在for循环中的控制变量,如果是全局变量的话,一定慎重操作,或者直接写里边,在用到的时候再调出来,这样可以避免不必要的错误。

#include 
#include 
#include 
using namespace std;

int oil[110][110],m,n;
int main()
{
    int count;
    int cat[8][2] = {{1,0},{1,1},{0,1},{-1,1},{-1,0},{-1,-1},{0,-1},{1,-1}};
    while(cin >> m >> n && m != 0)
    {
        memset(oil,0,sizeof(oil));count = 0;
        int i,j;
        for(i = 1;i <= m;i ++)
        for(j = 1;j <= n;j ++)
        {
            char temp;
            cin >> temp;
            oil[i][j] = (temp == '*'? 0 : 1);
        }
        for(i = 1;i <= m;i ++)
        for(j = 1;j <= n;j ++)
        if(oil[i][j] == 1)
        {
            count = count + 1;
            queue q;
            q.push(i);q.push(j);
            while(!q.empty())
            {
                int x1,y1,x2,y2;
                x1 = q.front();q.pop();y1 = q.front();q.pop();
                oil[x1][y1] = 0;
                for(int ii = 0;ii < 8;ii ++)
                {
                    x2 = x1 + cat[ii][0];y2 = y1 + cat[ii][1];
                    if(oil[x2][y2] == 1)
                    {
                        q.push(x2);q.push(y2);
                        oil[x2][y2] = 0;
                    }
                }
            }

        }
        cout << count << endl;
    }
    return 0;
}

你可能感兴趣的:(hdu)