jps+ 구현을 찾고 rust 코드로 작성해줘
- User
jps+ 구현을 찾고 rust 코드로 작성해줘
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
jps+ 구현을 찾고 rust 코드로 작성해줘
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
네, JPS+ (Jump Point Search Plus) 알고리즘의 Rust 구현을 찾아 Rust 코드로 작성해 드릴 수 있습니다. JPS+는 그리드 기반 맵에서 A* 알고리즘의 성능을 개선한 경로 탐색 알고리즘으로, 불필요한 노드 탐색을 줄이기 위해 '점프 포인트'라는 개념을 사용합니다.
아래는 JPS+의 핵심 개념을 포함한 Rust 코드 예시입니다. 이 코드는 기본적인 그리드 표현, 노드 관리, 우선순위 큐, 점프 포인트 식별 및 경로 재구성 기능을 포함합니다.
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use std::f32;
// --- 기본 구조체 정의 ---
// 2D 좌표를 나타내는 구조체
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Point {
x: i32,
y: i32,
}
impl Point {
fn new(x: i32, y: i32) -> Self {
Point { x, y }
}
// 맨해튼 거리 계산 (Heuristic)
fn distance(&self, other: &Point) -> f32 {
((self.x - other.x).abs() + (self.y - other.y).abs()) as f32
}
// 두 점 사이의 방향 벡터 (dx, dy) 계산
fn direction_to(&self, other: &Point) -> (i32, i32) {
((other.x - self.x).signum(), (other.y - self.y).signum())
}
}
// 그리드 맵 표현
struct Grid {
width: i32,
height: i32,
obstacles: HashSet<point>,
}
impl Grid {
fn new(width: i32, height: i32, obstacles: HashSet<point>) -> Self {
Grid { width, height, obstacles }
}
// 해당 위치가 유효하고 이동 가능한지 확인
fn is_walkable(&self, p: Point) -> bool {
p.x >= 0 && p.x < self.width && p.y >= 0 && p.y < self.height && !self.obstacles.contains(&p)
}
}
// A* 및 JPS+ 탐색에 사용될 노드
#[derive(Debug, Clone)]
struct Node {
point: Point,
g_cost: f32, // 시작점부터 현재 노드까지의 비용
h_cost: f32, // 현재 노드부터 목표점까지의 추정 비용 (Heuristic)
f_cost: f32, // g_cost + h_cost
parent: Option<point>, // 경로 재구성을 위한 부모 노드 좌표
}
impl Node {
fn new(point: Point, g_cost: f32, h_cost: f32, parent: Option<point>) -> Self {
Node {
point,
g_cost,
h_cost,
f_cost: g_cost + h_cost,
parent,
}
}
}
// 우선순위 큐 (Min-Heap) 를 위한 비교 로직 구현
// f_cost가 낮은 노드가 우선순위가 높다 (BinaryHeap은 Max-Heap이므로 역순으로 비교)
impl Ord for Node {
fn cmp(&self, other: &Self) -> Ordering {
other.f_cost.partial_cmp(&self.f_cost).unwrap_or(Ordering::Equal)
}
}
impl PartialOrd for Node {
fn partial_cmp(&self, other: &Self) -> Option<ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Node {
fn eq(&self, other: &Self) -> bool {
self.f_cost == other.f_cost // 우선순위 큐에서는 f_cost 기준으로 비교
// 실제 노드의 동일성은 point로 판단해야 함
}
}
impl Eq for Node {}
// --- JPS+ 알고리즘 구현 ---
struct JpsPlus<'a> {
grid: &'a Grid,
start: Point,
goal: Point,
open_set: BinaryHeap<node>, // 탐색할 노드 (우선순위 큐)
closed_set: HashSet<point>, // 이미 탐색한 노드 좌표
came_from: HashMap<point, point="">, // 경로 재구성을 위한 맵 (자식 -> 부모)
g_costs: HashMap<point, f32="">, // 각 노드까지의 최소 g_cost 저장
}
impl<'a> JpsPlus<'a> {
fn new(grid: &'a Grid, start: Point, goal: Point) -> Self {
let mut open_set = BinaryHeap::new();
let mut g_costs = HashMap::new();
let start_h_cost = start.distance(&goal);
let start_node = Node::new(start, 0.0, start_h_cost, None);
open_set.push(start_node);
g_costs.insert(start, 0.0);
JpsPlus {
grid,
start,
goal,
open_set,
closed_set: HashSet::new(),
came_from: HashMap::new(),
g_costs,
}
}
// JPS+ 경로 탐색 실행
fn find_path(&mut self) -> Option<vec<point>> {
while let Some(current_node) = self.open_set.pop() {
let current_point = current_node.point;
// 이미 더 나은 경로로 처리된 노드면 스킵 (우선순위 큐 특성상 중복 가능)
if current_node.g_cost > *self.g_costs.get(&current_point).unwrap_or(&f32::INFINITY) {
continue;
}
// 목표 지점 도달
if current_point == self.goal {
println!("Goal reached!");
return Some(self.reconstruct_path(current_point));
}
// 현재 노드를 closed set에 추가
self.closed_set.insert(current_point);
// 후계자 (점프 포인트) 식별 및 처리
self.identify_successors(&current_node);
}
// 경로를 찾지 못함
println!("Path not found.");
None
}
// 현재 노드의 후계자 (점프 포인트) 식별
fn identify_successors(&mut self, parent_node: &Node) {
let parent_point = parent_node.point;
let neighbors = self.find_neighbors(parent_node); // 강제 이웃 포함 이웃 탐색
for neighbor in neighbors {
// 직선 또는 대각선 점프 실행
if let Some(jump_point) = self.jump(neighbor, parent_point) {
if self.closed_set.contains(&jump_point) {
continue; // 이미 탐색 완료한 점프 포인트는 스킵
}
let new_g_cost = self.g_costs[&parent_point] + self.cost(parent_point, jump_point); // 부모에서 점프포인트까지의 실제 거리
// 기존 경로보다 더 나은 경로 발견 시 업데이트
if new_g_cost < *self.g_costs.get(&jump_point).unwrap_or(&f32::INFINITY) {
self.g_costs.insert(jump_point, new_g_cost);
self.came_from.insert(jump_point, parent_point); // 부모-자식 관계 기록
let h_cost = jump_point.distance(&self.goal);
let jump_node = Node::new(jump_point, new_g_cost, h_cost, Some(parent_point));
// open_set에 추가 (또는 기존 노드 업데이트 - BinaryHeap은 직접 업데이트 불가, 그냥 추가)
self.open_set.push(jump_node);
}
}
}
}
// JPS+의 핵심: 특정 방향으로 점프하여 다음 점프 포인트 탐색
fn jump(&self, current: Point, parent: Point) -> Option<point> {
if !self.grid.</point></vec<point></point,></point,></point></node></ordering></point></point></point></point>