概述
思路:
使用dfs判断遍历所有的点,同时在dfs的过程中检查点是否满足要求,并将访问过的点使用数组保存下来,注意返回值通过dfs的参数来返回(这个在深搜递归中挺好用的,如果不能确定何时结束)
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
void solve(vector<vector<char> > &board) {
for (int i = 0; i < board.size(); i++)
{
for (int j = 0; j < board[i].size(); j++)
{
if ((i<board.size()-1 && i>0 && j<board[i].size()-1 && j>0) && (board[i][j] == 'O' || board[i][j] == 'Y'))
{
board[i][j] = 'O';
vector<vector<int> > res;
vector<int> tmp;
bool flag = true;
tmp.push_back(i);
tmp.push_back(j);
res.push_back(tmp);
board[i][j] = 'Y';
dfs(board, i, j, res, flag);
if (flag)
{
for (int k = 0; k < res.size(); k++)
{
board[res[k][0]][res[k][1]] = 'X';
}
}
else
{
for (int k = 0; k < res.size(); k++)
{
board[res[k][0]][res[k][1]] = 'O';
}
}
}
}
}
}
void dfs(vector<vector<char> > &board, int x, int y, vector<vector<int> > &res, bool &flag)
{
int a[4][2] = { { 1, 0 },{ -1, 0 },{ 0, 1 },{ 0, -1 } };
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 2; j++)
{
int index_x = a[i][0];
int index_y = a[i][1];
if ((x + index_x<board.size() - 1 && x + index_x>0 && y + index_y<board[x].size() - 1 && y + index_y>0) && board[x + index_x][y + index_y] == 'O')
{
vector<int> tmp;
/*记录下坐标值*/
tmp.push_back(x + index_x);
tmp.push_back(y + index_y);
res.push_back(tmp);
board[x + index_x][y + index_y] = 'Y';
dfs(board, x + index_x, y + index_y, res, flag);
}
else if ((((x+index_x==board.size()-1 || x+index_x==0) && (y+index_y<board[x].size() && y+index_y>=0)) ||
((y+index_y==board[x].size()-1 || y+index_y==0) && (x+index_x<board.size() && x+index_x>=0)))
&& board[x+index_x][y+index_y]=='O')
{
/*如果该点为'O',但是位于边缘处*/
flag = false;
}
}
}
}
};
int main()
{
vector<vector<char> > board;
vector<char> test_0(6, 'O');
test_0[4] = 'X'; test_0[3] = 'X';
board.push_back(test_0);
vector<char> test_1(6, 'O');
board.push_back(test_1);
vector<char> test_2(6, 'O');
test_2[1] = 'X';test_2[3] = 'X';
board.push_back(test_2);
vector<char> test_3(6, 'O');
test_3[1] = 'X';test_3[4]='X';
board.push_back(test_3);
vector<char> test_4(6, 'O');
test_4[1] = 'X'; test_4[3]='X';
board.push_back(test_4);
vector<char> test_5(6, 'O');
test_5[1] = 'X';
board.push_back(test_5);
Solution S;
S.solve(board);
for (int i = 0; i < board.size(); i++)
{
for (int j = 0; j < board[i].size(); j++)
{
cout << board[i][j] << " ";
}
cout << endl;
}
system("pause");
return 0;
}
最后
以上就是整齐书包为你收集整理的LeetCode【surrounded-regions】的全部内容,希望文章能够帮你解决LeetCode【surrounded-regions】所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复