标签:
题目描述:public class Solution { public void Solve(char[,] board) { var row = board.GetLength(0); var col = board.GetLength(1); if(row < 2 || col < 2){ return; } // try go from left & right boundary var q = new Queue<Pos>(); for(var i = 0;i < row; i++){ if(board[i , 0] == ‘O‘){ q.Enqueue(new Pos(i , 0)); } if(board[i , col - 1] == ‘O‘){ q.Enqueue(new Pos(i , col - 1)); } } // try go from top & down boundary for(var i = 0;i < col; i++){ if(board[0,i] == ‘O‘){ q.Enqueue(new Pos(0 , i)); } if(board[row - 1 , i] == ‘O‘){ q.Enqueue(new Pos(row - 1 , i)); } } Bfs(ref board, row, col , q); // restore ‘A‘ to ‘O‘ // mark ‘O‘ to ‘X‘ for(var i = 0;i < row; i++){ for(var j = 0;j < col; j++){ if(board[i,j] == ‘O‘){ board[i,j] = ‘X‘; } if(board[i,j] == ‘A‘){ board[i,j] = ‘O‘; } } } } private void Bfs(ref char[,] board, int rowLen, int colLen, Queue<Pos> q) { if(q.Count == 0){ return; } var q1 = new Queue<Pos>(); while(q.Count > 0){ var p = q.Dequeue(); board[p.row, p.col] = ‘A‘; // move up if(p.row > 0 && board[p.row - 1, p.col] == ‘O‘){ q1.Enqueue(new Pos(p.row - 1, p.col)); } // move down if(p.row < rowLen - 1 && board[p.row + 1, p.col] == ‘O‘){ q1.Enqueue(new Pos(p.row + 1, p.col)); } // move right if(p.col < colLen - 1 && board[p.row, p.col + 1] == ‘O‘){ q1.Enqueue(new Pos(p.row, p.col + 1)); } // move left if(p.col > 0 && board[p.row, p.col - 1] == ‘O‘){ q1.Enqueue(new Pos(p.row, p.col - 1)); } } Bfs(ref board, rowLen, colLen, q1); } class Pos{ public Pos(int r, int c){ row = r; col = c; } public int row; public int col; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode -- Surrounded Regions
标签:
原文地址:http://blog.csdn.net/lan_liang/article/details/49885375