class Solution {
public:
vector<pair<int,int>> BFS(int curX, int curY, vector<vector<char>> &board, vector<vector<bool>>& visited, bool& bFilp)
{
int n = board.size();
int m = board[0].size();
int dir[4][2] = {{0,1}, {0,-1}, {1,0}, {-1,0}};
queue<pair<int, int>> q;
visited[curX][curY] = true;
q.push(make_pair(curX, curY));
vector<pair<int,int>> path;
while (!q.empty())
{
int x = q.front().first;
int y = q.front().second;
path.push_back(q.front());
q.pop();
for (int i = 0; i < 4; ++i)
{
int nextX = x+dir[i][0];
int nextY = y+dir[i][1];
if(nextX >= 0 && nextX < n && nextY >= 0 && nextY < m)
{
if(!visited[nextX][nextY] && board[nextX][nextY] == 'O')
{
q.push(make_pair(nextX, nextY));
visited[nextX][nextY] = true;
}
}
else bFilp = false;
}
}
return path;
}
void solve(vector<vector<char>> &board) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n = board.size();
if(n == 0) return;
int m = board[0].size();
vector<vector<bool>> visited;
visited.resize(n);
for(int i = 0; i < n; ++i)
visited[i].assign(m, false);
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
if(!visited[i][j] && board[i][j] == 'O')
{
bool bFlip = true;
vector<pair<int,int>> path = BFS(i, j, board, visited, bFlip);
if(bFlip)
{
for (int pIdx = 0; pIdx < path.size(); ++pIdx)
board[path[pIdx].first][path[pIdx].second] = 'X';
}
}
}
}
}
};
second time
class Solution {
public:
int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
void solveUtil(vector<vector<char> >& board, vector<vector<bool> >& visited, int ix, int iy, vector<pair<int,int> >& curPath, bool& isSurrounded)
{
int n = board.size();
int m = board[0].size();
queue<pair<int,int> > posQ;
posQ.push(pair<int,int>(ix, iy));
while(!posQ.empty())
{
int curX = posQ.front().first;
int curY = posQ.front().second;
posQ.pop();
if(board[curX][curY] == 'O' && !visited[curX][curY])
{
curPath.push_back(pair<int,int>(curX, curY));
visited[curX][curY] = true;
for(int k = 0; k < 4; ++k)
{
int newX = curX+dir[k][0];
int newY = curY+dir[k][1];
if(newX < 0 || newX >= n || newY < 0 || newY >= m) isSurrounded = false;
else if (!visited[newX][newY]) posQ.push(pair<int,int>(newX, newY));
}
}
}
}
void solve(vector<vector<char>> &board) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n = board.size();
if(n == 0) return;
int m = board[0].size();
vector<vector<bool> > visited(n, vector<bool>(m, false));
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < m; ++j)
{
vector<pair<int, int> > curPath;
bool isSurrounded = true;
if(!visited[i][j]) solveUtil(board, visited, i, j, curPath, isSurrounded);
if(isSurrounded)
{
for(int i = 0; i < curPath.size(); ++i)
board[curPath[i].first][curPath[i].second] = 'X';
}
}
}
}
};
502

被折叠的 条评论
为什么被折叠?



