LeetCode130-被围绕的区域 DFS与BFS (NOIP c++ 代码)

题目描述

给定一个二维的矩阵,包含 'X' 和 'O'字母 O)。找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。

// floodfill-dfs.cpp
#include
using namespace std;
vector vst;
void dfs(vector & board,int i,int j)
{
	if(i<0||j<0||i>board.size()-1||j>board[0].size()-1)
		return ;
	if(board[i][j]!='O')
		return;
	board[i][j]='V';
	dfs(board,i+1,j);
	dfs(board,i,j+1);
	dfs(board,i-1,j);
	dfs(board,i,j-1);
}
void solve(vector & board)
{
	if(board.empty()||board.size()==1||board[0].size()==1)return;
	for(int i=0; i > board(4,vector(4,'X'));
	vst.push_back("XXXX");
	vst.push_back("XOOX");
	vst.push_back("XXOX");
	vst.push_back("XOXX");
	solve(vst);
	for(int i=0; i
//floodfill-bfs
#include
using namespace std;
/*vector  b = {
	{'X','X','X','X'},
	{'X','O','O','X'},
	{'X','X','O','X'},
	{'X','O','X','X'}
};*/
vector vst;



struct pos {
	int x, y;
};
void visit(queue &mypos, int x, int y,
           vector& board)
{
	pos p= {x, y};
	mypos.push(p);
	board[x][y] = '*';
}
void solve(vector& board)//vector > & board)
{
	int row = board.size();
	if(row == 0)
		return;
	int col = board[0].size();

	if(row <= 2 || col <= 2)
		return;
	cout<<"输入:"< mypos;
	for(int i = 0; i < col; i++) {
		if(board[0][i] == 'O') {
			visit(mypos, 0, i, board);
		}
		if(board[row-1][i] == 'O') {
			visit(mypos, row-1, i, board);
		}
	}
	for(int i = 1; i < row-1; i++) {
		if(board[i][0] == 'O') {
			visit(mypos, i, 0, board);
		}
		if(board[i][col-1] == 'O') {
			visit(mypos, i, col-1, board);
		}
	}


	while(!mypos.empty()) {
		pos t = mypos.front();
		mypos.pop();
		if(t.x-1 >= 0 && board[t.x-1][t.y] == 'O')
			visit(mypos, t.x-1, t.y, board);
		if(t.x+1 < row && board[t.x+1][t.y] == 'O')
			visit(mypos, t.x+1, t.y, board);
		if(t.y-1 >= 0 && board[t.x][t.y-1] == 'O')
			visit(mypos, t.x, t.y-1, board);
		if(t.y+1 < col && board[t.x][t.y+1] == 'O')
			visit(mypos, t.x, t.y+1, board);
	}

	for(int i = 0; i < row; i++) {
		for(int j = 0; j < col; j++) {
			if(board[i][j] == 'O')
				board[i][j] = 'X';

			else if(board[i][j] == '*')
				board[i][j] = 'O';
		}
	}
	cout<<"矩阵变为:"<

 

你可能感兴趣的:(C/C++,NOIP普及,NOIP提高)