class Solution
{
public:
    void DFS(vector<vector<int>> &mark, vector<vector<char>> &grid, int x, int y)
    {                                          //深度搜索
        mark[x][y] = 1;                        //标记以搜索的位置
        static const int dx[] = {-1, 1, 0, 0}; //方向数组
        static const int dy[] = {0, 0, -1, 1};
        for (int i = 0; i < 4; i++)
        {
            int newx = dx[i] + x;
            int newy = dy[i] + y;
            if (newx < 0 || newx >= mark.size() || newy < 0 || newy >= mark[newx].size())
            { //超过数组边界时
                continue;
            }
            if (mark[newx][newy] == 0 && grid[newx][newy] == '1')
            {
                DFS(mark, grid, newx, newy);
            }
        }
    }
    int numIslands(vector<vector<char>> &grid)
    {
        int island_num = 0; //记载岛屿数量
        vector<vector<int>> mark;
        for (int i = 0; i < grid.size(); i++)
        {
            mark.push_back(vector<int>());
            for (int j = 0; j < grid[i].size(); j++)
            {
                mark[i].push_back(0);
            }
        }
        for (int i = 0; i < grid.size(); i++)
        {
            for (int j = 0; j < grid[i].size(); j++)
            {
                if (mark[i][j] == 0 && grid[i][j] == '1')
                {
                    DFS(mark, grid, i, j); //或BFS
                    island_num++;
                }
            }
        }
        return island_num;
    }
};