$$\text{distance measure}:~\text{Manhattan distance}=|x_2 - x_1 | + |y_2 - y_1|$$
Grassfire 알고리즘을 써서 최단경로를 찾는 문제는 DFS로도 구현할 수 있으나 비효율적이고(왜 그런지는 쉽게 알 수 있다) BFS로 구현하는 것이 더 적합하다.
void grassfire(CPoint q, int **map, int w, int h, int **dist) {
// left-top-right-bottom;
const int dx[] = {-1, 0, 1, 0};
const int dy[] = { 0, -1, 0, 1};
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
dist[y][x] = INF; //unvisited cells;
std::queue<CPoint> Q;
dist[q.y][q.x] = 0; //start( or end) position: distance = 0;
Q.push(q);
while (!Q.empty()) {
CPoint p = Q.front(); Q.pop();
int distance = dist[p.y][p.x];
// 4-way search;
for (int i = 0; i < 4; i++) {
CPoint q = CPoint(p.x + dx[i], p.y + dy[i]);
if (q.x < 0|| q.y < 0|| q.x >= w|| q.y >= h) continue;
if (map[q.y][q.x] == 0 && dist[q.y][q.x] == INF) {
dist[q.y][q.x] = distance + 1;
Q.push(q);
}
}
}
};
// back tracking;
CPoint back_track(CPoint p, int **dist, int w, in h) {
// left-top-right-bottom;
const int dx[] = {-1, 0, 1, 0};
const int dy[] = { 0, -1, 0, 1};
int depth = dist[p.y][p.x];
if (--depth < 0) return p;
for (int i = 0; i < 4; i++) {
CPoint q = CPoint(p.x + dx[i], p.y + dy[i]);
if (q.x < 0 || q.y < 0 || q.x >= w || q.y >= h) continue; // out of ROI;
else if (dist[q.y][q.x] == depth)
return q;
}
return p; // never hit;
}
728x90
'Image Recognition > Fundamental' 카테고리의 다른 글
Brute-Force Euclidean Distance Transform (0) | 2021.03.14 |
---|---|
이미지에 Poisson Noise 넣기 (0) | 2021.03.06 |
Image Sharpness (0) | 2021.02.25 |
Selection Sort (0) | 2021.02.25 |
Bubble Sort (0) | 2021.02.24 |