[Leetcode] surrounded regions

Source: Internet
Author: User

Change 'O' surrounded by 'x' to 'x '.

Method: Start from the peripheral 'O' and find the connectable 'O', then these 'O' will not be marked in the end, and the remaining 'O' will be marked. Here, we can mark the 'O' that can be traversed from the peripheral 'O' as another character, and then restore it in a unified manner. Method 2: it can also be explored from all 'O'. As long as it cannot be explored beyond the boundary, the intermediate nodes can be saved in a stack.

Implementation: BFS (using DFS will blow up stack re ...)

int dir[4][2]={-1,0,1,0,0,-1,0,1};struct Node{    int x,y;};class Solution {public:    int n,len,m;    Node*Q;    void bfs(int stx,int sty,vector<vector<char> > &b){        int front=-1,rear=-1,len=n*m;        Node p,q;        p.x=stx,p.y=sty;        b[p.x][p.y]='F';        Q[++rear]=p;        int i,dx,dy;        while(front!=rear){            front=(front+1)%len;            q=Q[front];         //   if(b[q.x][q.y]!='O')continue;            for(i=0;i<4;++i){                p.x=q.x+dir[i][0];                p.y=q.y+dir[i][1];                if(p.x<0||p.y<0||p.x>=n||p.y>=m||b[p.x][p.y]!='O')                    continue;                b[p.x][p.y]='F';                rear=(rear+1)%len;                Q[rear]=p;            }        }    }    void solve(vector<vector<char> > &b) {        if(b.size()<=0)return;        int i,j,k;        n=b.size();        m=b[0].size();        Q=new Node[n*m];        for(i=0;i<m;++i){            if(b[0][i]=='O')bfs(0,i,b);            if(b[n-1][i]=='O')bfs(n-1,i,b);        }        for(i=1;i<n-1;++i){            if(b[i][0]=='O')bfs(i,0,b);            if(b[i][m-1]=='O')bfs(i,m-1,b);        }        for(i=0;i<n;++i){            m=b[i].size();            for(j=0;j<m;++j)            {                if(b[i][j]=='F')b[i][j]='O';                else if(b[i][j]=='O')b[i][j]='X';            }        }        delete[]Q;    }};




[Leetcode] surrounded regions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.