1. 程式人生 > >Leetcode 130. Surrounded Regions

Leetcode 130. Surrounded Regions

class Solution{
public:
	void bfs(vector<vector<char>> &board, int r, int c)
	{
		board[r][c] = 'e';
		if (r-1 >= 0 && board[r-1][c] == 'O')
		{
			bfs(board, r-1, c);
		}
		if (r + 1 <= board.size() - 1 && board[r + 1][c] == 'O')
		{
			bfs(board, r + 1, c);
		}
		if (c - 1 >= 0 &&  board[r][c - 1] == 'O')
		{
			bfs(board, r, c - 1);
		}
		if (c + 1 <= board[0].size() - 2 && board[r][c + 1] == 'O')
		{
			bfs(board, r, c + 1);
		}
	}
	void solve(vector<vector<char>> &board) {
		if (board.size() == 0 || board[0].size() == 0)
			return;
		else if (board.size() <= 2 || board[0].size() <= 2)
			return;
		else
		{
			for (int i = 0; i < board[0].size(); i++)
			{
				if (board[0][i] == 'O')
					bfs(board, 0, i);
				if (board[board.size() - 1][i] == 'O')
					bfs(board, board.size() - 1, i);
			}
			for (int i = 0; i < board.size(); i++)
			{
				if (board[i][0] == 'O')
					bfs(board, i, 0);
				if (board[i][board[0].size()- 1] == 'O')
					bfs(board, i, board[0].size() - 1);
			}
			for (int i = 0; i < board.size(); i++)
			{
				for (int j = 0; j < board[0].size(); j++)
				{
					if (board[i][j] == 'e')
					{
						board[i][j] = 'O';
					}
					else
					{
						board[i][j] = 'X';
					}
				}
			}
		}
	}
};