leetcodeに投稿された囲まれた領域の問題を解決するアルゴリズムを考え出しました。
しかし悲しいことに、私のソリューションは最初のジャッジ入力セットでは合格できますが、2 番目の大きな入力セットでは合格できず、実行時エラーが報告されます。ただし、ラップトップでは正常に実行できます。私はこの問題に何時間も費やしましたが、まだわかりません!
以下が問題です。
「X」と「O」を含む 2D ボードが与えられた場合、「X」で囲まれたすべての領域をキャプチャします。
リージョンは、囲まれたリージョン内のすべての「O」を「X」に反転することによってキャプチャされます。
例えば、
XXXX
XOOX
XXOX
XOXX
関数を実行すると、ボードは次のようになります。
XXXX
XXXX
XXXX
XOXX
以下は私の解決策です:
class Solution {
public:
void solve(vector<vector<char> > &board) {
if(board.size() == 0) return;
int row = board.size();
set<pair<int, int> > map;
for(int i=0; i<= row/2; i++){
int bottom = row-i-1;
for(int j=i; j<= bottom; j++){
checkPoint(board, i, j, map);
checkPoint(board, bottom, j, map);
checkPoint(board, j, i, map);
checkPoint(board, j, bottom, map);
}
}
}
void mark(vector<vector<char> >& board, int row, int col, set<pair<int, int> >& map){
if(row < 0 || row > board.size()-1 || col < 0 || col > board[0].size()-1 )
return;
int temp = col;
while(temp-1 >= 0 && board[row][temp-1] == 'O' &&\
map.find(pair<int,int>(row, temp-1)) == map.end()){
map.insert(pair<int, int>(row, temp-1));
temp -=1;
mark(board, row, temp, map);
}
temp = col;
while(temp+1 <= board[0].size()-1 && board[row][temp+1] == 'O' && \
map.find(pair<int,int>(row, temp+1)) == map.end()){
map.insert(pair<int, int>(row, temp+1));
temp +=1;
mark(board, row, temp, map);
}
temp = row;
while(temp -1 >= 0 && board[temp-1][col] == 'O'&& \
map.find(pair<int,int>(temp-1, col)) == map.end()){
map.insert(pair<int, int>(temp-1, col));
temp -=1;
mark(board, temp, col, map);
}
temp = row;
while(temp+1 <= board.size()-1 && board[temp+1][col] == 'O'&& \
map.find(pair<int,int>(temp+1, col)) == map.end()){
map.insert(pair<int, int>(temp+1, col));
temp +=1;
mark(board, temp, col, map);
}
}
void checkPoint(vector<vector<char> >& board, int row, int col, set<pair<int, int> >& map){
if(board[row][col] == 'O'){
if(row ==0 || col== 0 || row == board.size()-1 || col == board[0].size()-1 ){
if(map.find(pair<int, int>(row, col)) == map.end()){
map.insert(pair<int,int>(row, col));
mark(board, row, col, map);
}
}else if(map.find(pair<int, int>(row, col)) == map.end()){
board[row][col] = 'X';
}
}
return;
}
};