LeetCode(200)Number of Islands

来源:互联网 发布:百度音乐人的域名 编辑:程序博客网 时间:2024/06/06 14:53

BFS广度优先搜索

class Solution {public:    void bfs(vector<vector<char>>& grid, int i, int j, int length, int width) {        queue<pair<int, int>> que;        grid[i][j] = '#';        que.push(make_pair(i, j));        while(!que.empty()) {            int row = que.front().first;            int column = que.front().second;            if(row - 1 >= 0 && grid[row - 1][column] == '1') {                grid[row - 1][column] = '#';                que.push(make_pair(row - 1, column));            }            if(row + 1 < length && grid[row + 1][column] == '1') {                grid[row + 1][column] = '#';                que.push(make_pair(row + 1, column));            }            if(column - 1 >= 0 && grid[row][column - 1] == '1') {                grid[row][column - 1] = '#';                que.push(make_pair(row, column - 1));            }            if(column + 1 < width && grid[row][column + 1] == '1') {                grid[row][column + 1] = '#';                que.push(make_pair(row, column + 1));            }            que.pop();        }    }    int numIslands(vector<vector<char>>& grid) {        if(grid.size() == 0)            return 0;        int length = grid.size();        int width = grid[0].size();        int counter = 0;        for(int i = 0; i < length; i++) {            for(int j = 0; j < width; j++) {                if(grid[i][j] == '1') {                    counter++;                    bfs(grid, i, j, length, width);                }            }        }        return counter;    }};
0 0