Surrounded regions (Graph; DFS)

Source: Internet
Author: User

Given a 2D board containing ‘X‘ ‘O‘ and, capture all regions surrounded by ‘X‘ .

A region was captured by flipping all ‘O‘ s into ‘X‘ s-surrounded region.

For example,

x x x xx o o xx x o xx o x x

After running your function, the board should is:

x x x xx x x xx x x xx O x x

Idea: Starting with the ' 0 ' on the four side, the ' O ' adjacent to it is not changed, and is recorded as ' D '. Reverse Thinking! Never be changed ' o ' instead of looking for being changed ' o '

classSolution { Public:       voidDfsintXinty) {        if(x<0|| X>=m | | y<0|| Y>=n | | board[x][y]!='O')return; Board[x][y]='D'; //four-direction traversal of a graphDFS (X-1, y); DFS (x+1, y); DFS (x, y-1); DFS (x, y+1); }        voidSolve (vector<vector<Char>> &Board) {        if(Board.empty ())return;  This->board =Board; M=board.size (); N=board[0].size (); if(n<=2|| m<=2)return;  for(intj=0; j<n;j++) {DFS (0, J); DFS (M-1, J); }                 for(intI=1; i<m;i++) {DFS (I,0); DFS (I,n-1); }                 for(intI=0; i<m;i++)             for(intj=0; j<n;j++){                if( This->board[i][j]=='O') This->board[i][j]='X'; Else if( This->board[i][j]=='D') This->board[i][j]='O'; } Board= This-Board; }Private:     intM,n; Vector<vector<Char>>board;};

Surrounded regions (Graph; DFS)

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.