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(JPS) 알고리즘의 성능을 극적으로 향상시키는 방법입니다. JPS는 A* 기반의 그리드 경로 탐색에서 "점프 포인트"만을 확장하여 불필요한 노드 탐색을 줄이지만, JPS+는 여기에 더해 **각 그리드 셀에서 8방향으로 점프할 수 있는 최종 점프 포인트를 미리 계산(전처리)**하여, 런타임에는 단순히 테이블 조회만으로 빠르게 경로를 탐색합니다[4].
아래는 2D 격자 맵에서 JPS+의 핵심 구조와 동작을 단순화하여 Rust로 구현한 예시입니다.
(실제 게임/서비스용으로는 메모리 최적화, 장애물 동적 갱신, 경계 체크 등 추가 구현 필요)
use std::collections::{BinaryHeap, HashMap};
use std::cmp::Ordering;
const DIRS: [(i32, i32); 8] = [
(0, -1), // N
(1, -1), // NE
(1, 0), // E
(1, 1), // SE
(0, 1), // S
(-1, 1), // SW
(-1, 0), // W
(-1, -1), // NW
];
#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
struct Pos {
x: usize,
y: usize,
}
#[derive(Clone, Eq, PartialEq)]
struct Node {
pos: Pos,
g: usize,
f: usize,
}
impl Ord for Node {
fn cmp(&self, other: &Self) -> Ordering {
// BinaryHeap은 max-heap이므로, f가 작은 것이 우선
other.f.cmp(&self.f)
}
}
impl PartialOrd for Node {
fn partial_cmp(&self, other: &Self) -> Option<ordering> {
Some(self.cmp(other))
}
}
// 전처리 테이블: [y][x][dir] = Option<pos>
type JumpTable = Vec<vec<[option<pos>; 8]>>;
// 맵: true = 통과 가능, false = 장애물
type Map = Vec<vec<bool>>;
// 휴리스틱 (맨해튼 거리)
fn heuristic(a: &Pos, b: &Pos) -> usize {
((a.x as isize - b.x as isize).abs() + (a.y as isize - b.y as isize).abs()) as usize
}
// 전처리: 각 셀에서 8방향으로 점프 가능한 최종 점프 포인트 계산
fn preprocess_jps_plus(map: ⤅) -> JumpTable {
let h = map.len();
let w = map.len();
let mut table = vec![vec![[None; 8]; w]; h];
for y in 0..h {
for x in 0..w {
if !map[y][x] { continue; }
for (dir_idx, &(dx, dy)) in DIRS.iter().enumerate() {
let mut cx = x as i32;
let mut cy = y as i32;
loop {
let nx = cx + dx;
let ny = cy + dy;
if nx < 0 || ny < 0 || nx >= w as i32 || ny >= h as i32 {
break;
}
if !map[ny as usize][nx as usize] {
break;
}
cx = nx;
cy = ny;
}
// 마지막 유효 위치가 점프 포인트
if (cx as usize, cy as usize) != (x, y) {
table[y][x][dir_idx] = Some(Pos { x: cx as usize, y: cy as usize });
}
}
}
}
table
}
// JPS+ 경로 탐색
fn jps_plus_search(
map: ⤅,
jump_table: &JumpTable,
start: Pos,
goal: Pos,
) -> Option<vec<pos>> {
let mut open = BinaryHeap::new();
let mut came_from: HashMap<pos, pos=""> = HashMap::new();
let mut g_score: HashMap<pos, usize=""> = HashMap::new();
g_score.insert(start, 0);
open.push(Node { pos: start, g: 0, f: heuristic(&start, &goal) });
while let Some(Node { pos, g, .. }) = open.pop() {
if pos == goal {
// 경로 복원
let mut path = vec![pos];
let mut current = pos;
while let Some(&prev) = came_from.get(&current) {
path.push(prev);
current = prev;
}
path.reverse();
return Some(path);
}
for dir_idx in 0..8 {
if let Some(jump_pos) = jump_table[pos.y][pos.x][dir_idx] {
let tentative_g = g + heuristic(&pos, &jump_pos);
if tentative_g < *g_score.get(&jump_pos).unwrap_or(&usize::MAX) {
g_score.insert(jump_pos, tentative_g);
let f = tentative_g + heuristic(&jump_pos, &goal);
open.push(Node { pos: jump_pos, g: tentative_g, f });
came_from.insert(jump_pos, pos);
}
}
}
}
None
}
// 예시 사용법
fn main() {
// 5x5 맵, true=통과 가능, false=장애물
let map = vec![
vec![true, true, true, true, true],
vec![true, false, false, false, true],
vec![true, true, true, true, true],
vec![true, false, false, false, true],
vec![true, true, true, true, true],
];
let jump_table = preprocess_jps_plus(↦);
let start = Pos { x: 0, y: 0 };
let goal = Pos { x: 4, y: 4 };
if let Some(path) = jps_plus_search(↦, &jump_table, start, goal) {
println!("Path: {:?}", path);
} else {
println!("No path found");
}
}
came_from 맵을 따라 경로를 역추적합니다.이 코드는 JPS+의 핵심 원리를 보여주는 예시이며, 실제 서비스에서는 메모리 최적화, 장애물 동적 갱신, 경계 체크, 대각선 이동 비용 등 추가 구현이 필요합니다.
JPS+의 전처리와 탐색 구조를 Rust로 구현할 때의 기본 골격으로 참고할 수 있습니다.