码迷,mamicode.com
首页 > 其他好文 > 详细

130. Surrounded Regions

时间:2016-09-23 06:33:07      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

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

A region is captured by flipping all ‘O‘s into ‘X‘s in that surrounded region.

For example,

X X X X
X O O X
X X O X
X O X X

 

After running your function, the board should be:

X X X X
X X X X
X X X X
X O X X

public void Solve(char[,] board) {
        if(board.GetLength(0)==0 || board.GetLength(0)==0 ) return;
        int rowLength = board.GetLength(0);
        int colLength = board.GetLength(1);
 
        for(int i = 0;i<rowLength;i++)
        {
            for(int j = 0;j<colLength;j++)
            {
                if((i==0||j==0||i == rowLength-1 || j == colLength -1)&&(board[i,j]==O))
                {
                    DFS(board,i,j);
                }
            }
        }
        for(int i = 0;i<rowLength;i++)
        {
            for(int j = 0;j<colLength;j++)
            {
               if(board[i,j]==T)  board[i,j]=O;
               else if(board[i,j]==O)  board[i,j]=X;
            }
        }
        return;
        
    }
    
    private void DFS(char[,] board, int row, int col)
    {
        board[row,col] = T;
        if(row>0 && board[row-1,col] == O) DFS(board,row-1,col);
        if(row<(board.GetLength(0)-1) && board[row+1,col] == O) DFS(board,row+1,col);
        if(col>1 && board[row,col-1] == O) DFS(board,row,col-1);
        if(col<(board.GetLength(1)-1) && board[row,col+1] == O) DFS(board,row,col+1);
    }

 

130. Surrounded Regions

标签:

原文地址:http://www.cnblogs.com/renyualbert/p/5898535.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!