leetcode 130: Surrounded Regions

来源:互联网 发布:域名污染 gfw 编辑:程序博客网 时间:2024/05/16 17:58

The algorithm is not so hard to think. Just try from the boarder, if there is an 'O', DFS or BFS and change all 'O's in that region to another character. After that, change all 'O's to 'X' and all different characters (I use 'n') to 'O'. The trick when using BFS here is to change the character before push into the queue, or it will push some positions that are already in the queue and finally cause TLE.

class Solution {public:    void solve(vector<vector<char>>& board) {        if(board.empty())            return;        int m=board.size();        int n=board[0].size();        for(int i=0;i<m;i++)        {            if(board[i][0]=='O')                bfs(board,i,0,m,n);            if(board[i][n-1]=='O')                bfs(board,i,n-1,m,n);        }        for(int i=0;i<n;i++)        {            if(board[0][i]=='O')                bfs(board,0,i,m,n);            if(board[m-1][i]=='O')                bfs(board,m-1,i,m,n);        }        for(int i=0;i<m;i++)            for(int j=0;j<n;j++)            {                if(board[i][j]=='O')                    board[i][j]='X';                else if(board[i][j]=='n')                    board[i][j]='O';            }    }    void bfs(vector<vector<char> >& board,int r,int c,int m,int n)    {        queue<pair<int,int> > q;        board[r][c]='n';        q.push(make_pair(r,c));        while(!q.empty())        {            r=q.front().first;            c=q.front().second;            q.pop();            if(r>0&&board[r-1][c]=='O')            {                board[r-1][c]='n';                q.push(make_pair(r-1,c));            }            if(r<m-1&&board[r+1][c]=='O')            {                board[r+1][c]='n';                q.push(make_pair(r+1,c));            }            if(c>0&&board[r][c-1]=='O')            {                board[r][c-1]='n';                q.push(make_pair(r,c-1));            }            if(c<n-1&&board[r][c+1]=='O')            {                board[r][c+1]='n';                q.push(make_pair(r,c+1));            }        }    }};


0 0
原创粉丝点击