最近做一些需求,发现 BFS 还挺好使,经常用, 主要是用于 特定目的 的连通区域分析
理论上 深度优先搜索也可以达到同样效果,但实际运用时发现 基于栈实现深度优先搜索在处理 比较大的连通区域时 导致 栈溢出, 那么还是使用 BFS 吧。
// i - row,
void bfsFix(int i, int j, cv::Mat & img, int thresholdValue, int destValue) {
int m = img.rows;
int n = img.cols;
int dx[8] = { -1, -1, -1, 0, 1, 1, 1, 0 };
int dy[8] = { -1, 0, 1, 1, 1, 0, -1, -1 };
std::queue<cv::Point> que;
que.push(cv::Point(j, i));
img.at<uchar>(i, j) = destValue;
while (!que.empty()) {
auto head = que.front();
que.pop();
for (int k = 0; k < 8; k++) {
int newX = head.x + dx[k];
int newY = head.y + dy[k];
if (newX >= 0 && newX < n && newY >= 0 && newY < m) {
if (img.at<uchar>(newY, newX) >= thresholdValue) {
img.at<uchar>(newY, newX) = destValue;
que.push(cv::Point(newX, newY));
}
}
}
}
}