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+는 기존 JPS(Jump Point Search) 알고리즘의 성능을 극적으로 개선한 버전입니다. JPS는 A* 기반의 경로 탐색에서 "점프 포인트"만을 확장하여 불필요한 노드 확장을 줄이는 방식입니다. JPS+는 여기에 더해 모든 그리드 셀에 대해 8방향의 점프 결과를 미리 계산(전처리) 해두고, 탐색 시 이 정보를 즉시 활용하여 Grid Scanning(점프 탐색) 시간을 획기적으로 줄입니다.
이 방식은 특히 맵이 자주 변하지 않는(정적 맵) 환경에서 매우 빠른 경로 탐색이 가능합니다[4].
> "JPS+는 각 Grid마다 8방향의 JUMP POINT 관련 연산 정보들을 모두 선 계산한 후 저장을 해서 Grid Scanning 시간 전체를 줄이는 방법으로 성능 향상을 이루고 있어요."[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, PartialEq, Eq, Hash, Debug)]
struct Point {
x: usize,
y: usize,
}
#[derive(Clone, Debug)]
struct JumpTable {
// For each cell, for each direction, store the next jump point (or None)
table: Vec<vec<[option<point>; 8]>>,
}
impl JumpTable {
fn new(map: &Vec<vec<bool>>) -> Self {
let height = map.len();
let width = map.len();
let mut table = vec![vec![[None; 8]; width]; height];
for y in 0..height {
for x in 0..width {
if !map[y][x] { continue; } // Skip obstacles
for (dir_idx, &(dx, dy)) in DIRS.iter().enumerate() {
let mut nx = x as i32;
let mut ny = y as i32;
loop {
nx += dx;
ny += dy;
if nx < 0 || ny < 0 || nx >= width as i32 || ny >= height as i32 {
break;
}
if !map[ny as usize][nx as usize] {
break;
}
// Jump point 조건: 대각선/직선에서 forced neighbor가 있으면 점프 포인트
// 여기서는 단순화: 장애물 앞까지 점프
table[y][x][dir_idx] = Some(Point { x: nx as usize, y: ny as usize });
}
}
}
}
JumpTable { table }
}
fn jump(&self, from: &Point, dir_idx: usize) -> Option<point> {
self.table[from.y][from.x][dir_idx]
}
}
#[derive(Copy, Clone, Eq, PartialEq)]
struct State {
cost: usize,
pos: Point,
}
impl Ord for State {
fn cmp(&self, other: &Self) -> Ordering {
// Min-heap
other.cost.cmp(&self.cost)
}
}
impl PartialOrd for State {
fn partial_cmp(&self, other: &Self) -> Option<ordering> {
Some(self.cmp(other))
}
}
// 휴리스틱: 맨해튼 거리
fn heuristic(a: &Point, b: &Point) -> usize {
((a.x as isize - b.x as isize).abs() + (a.y as isize - b.y as isize).abs()) as usize
}
// JPS+ 기반 경로 탐색
fn jps_plus_search(
map: &Vec<vec<bool>>,
jump_table: &JumpTable,
start: Point,
goal: Point,
) -> Option<vec<point>> {
let mut open = BinaryHeap::new();
let mut came_from: HashMap<point, point=""> = HashMap::new();
let mut g_score: HashMap<point, usize=""> = HashMap::new();
g_score.insert(start, 0);
open.push(State { cost: heuristic(&start, &goal), pos: start });
while let Some(State { cost: _, pos }) = 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_point) = jump_table.jump(&pos, dir_idx) {
let tentative_g = g_score[&pos] + heuristic(&pos, &jump_point);
if tentative_g < *g_score.get(&jump_point).unwrap_or(&usize::MAX) {
came_from.insert(jump_point, pos);
g_score.insert(jump_point, tentative_g);
let f = tentative_g + heuristic(&jump_point, &goal);
open.push(State { cost: f, pos: jump_point });
}
}
}
}
None
}
// 예시 사용법
fn main() {
// true: 통과 가능, false: 장애물
let map = vec![
vec![true, true, true, true, true],
vec![true, false, false, false, true],
vec![true, true, true, true, true],
];
let jump_table = JumpTable::new(↦);
let start = Point { x: 0, y: 0 };
let goal = Point { x: 4, y: 2 };
if let Some(path) = jps_plus_search(↦, &jump_table, start, goal) {
println!("Path: {:?}", path);
} else {
println!("No path found");
}
}