LeetCode.200

  无语的是,不知道为啥我的广搜最后一个测试点会TLE。。。

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        int nums = 0;
        for (int i = 0; i < grid.size(); i++)
        {
            for (int j = 0; j < grid[0].size(); j++)
            {
                if (grid[i][j] == '1')
                {
                    queue<pair<int, int>> q;
                    q.push(pair<int, int>(i, j));
                    int x = i, y = j;
                    do
                    {
                        x = q.front().first;
                        y = q.front().second;
                        grid[x][y] = '2';
                        q.pop();

                        if (y + 1 < grid[0].size() && grid[x][y + 1] == '1')
                            q.push(pair<int, int>(x, y + 1));
                        if (x + 1 < grid.size() && grid[x + 1][y] == '1')
                            q.push(pair<int, int>(x + 1, y));
                        if (y - 1 > -1 && grid[x][y - 1] == '1')
                            q.push(pair<int, int>(x, y - 1));
                        if (x - 1 > -1 && grid[x - 1][y] == '1')
                            q.push(pair<int, int>(x - 1, y));
                    } while (!q.empty());
                    nums++;
                }
            }
        }
        return nums;
    }
};

  

原文地址:https://www.cnblogs.com/darkchii/p/13578098.html