leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0200.cpp (925B)


      1 class Solution {
      2   public:
      3     int numIslands(vector<vector<char>> &grid) {
      4         queue<pair<int, int>> q;
      5         int cnt = 0;
      6         int m = grid.size(), n = grid[0].size();
      7         for (int i = 0; i < m; i++) {
      8             for (int j = 0; j < n; j++) {
      9                 if (grid[i][j] == '0') continue;
     10                 q.push(make_pair(i, j));
     11                 cnt++;
     12                 while (!q.empty()) {
     13                     int i = q.front().first;
     14                     int j = q.front().second;
     15                     q.pop();
     16                     if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == '0') continue;
     17                     grid[i][j] = '0';
     18                     q.push(make_pair(i + 1, j));
     19                     q.push(make_pair(i - 1, j));
     20                     q.push(make_pair(i, j + 1));
     21                     q.push(make_pair(i, j - 1));
     22                 }
     23             }
     24         }
     25         return cnt;
     26     }
     27 };