leetcode.200 number of islands

Given a two-dimensional grid by a '1' (land) and '0' (water) composition, the number of islands is calculated. An island surrounded by water, and it is through the horizontal or vertical direction is connected to each adjacent land. You can assume that the water surrounding the four sides of the grid are.

Example 1:

Enter:
11110
11010
11000
00000

Output: 1
Example 2:

Enter:
11000
11000
00100
00011

Output: 3

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/number-of-islands
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

 

Because in the past have done, so the copy, confused in x and y and the corresponding grid.size on () (), and gird [0] .size, so the overflow error occurs took a long time to check for errors.

 

class Solution {
public:
struct queue{
    int x[30000];
    int y[30000];
    int head,tail;
}qqq;
int visited[1000][1000];
int enqueue(int o,int p,vector<vector<char>>& grid){
    if((qqq.tail+1)%500==qqq.head){
        return 0;
    }
    if(o<0||o>=grid.size()||p<0||p>=grid[0].size()){
        return 0;
    }
    if(visited[o][p]!=0||grid[o][p]=='0'){
        return 0;
    }
    cout<<o<<" "<<p<<"enqueue\n";
    qqq.x[qqq.tail]=o;
    qqq.y[qqq.tail]=p;
    visited[o][p]=1;
    qqq.tail++;
    return 1;
}
int dequeue(){
    if(qqq.head==qqq.tail){
        return 0;
    }
    qqq.head++;
    return 1;
}
bool isempty(){
    if(qqq.head==qqq.tail){
        return true;
    }
    return false;
}
    int numIslands(vector<vector<char>>& grid) {
        if(grid.size()==0||grid[0].size()==0) return 0;
        int count=0;
    qqq.head=0;
    qqq.tail=0;
    int f,g;
    int i,j;
    for(i=0;i<grid.size();i++){
        for(j=0;j<grid[i].size();j++){
            visited[i][j]=0;
        }
    }
    for(i=0;i<grid.size();i++){
        for(j=0;j<grid[i].size();j++){
            if(grid[i][j]=='1'&&visited[i][j]==0){
            enqueue(i,j,grid);
            while (!isempty()){
                f=qqq.x[qqq.head];
                g=qqq.y[qqq.head];
                visited[f][g]=count+1;
                dequeue();
                enqueue(f-1,g,grid);
                enqueue(f+1,g,grid);
                enqueue(f,g+1,grid);
                enqueue(f,g-1,grid);
            }
            count++;
        }
    }
}
return count;
    }
};

Guess you like

Origin www.cnblogs.com/hyffff/p/12152667.html