From 913a3b7409e08fd239a65ff7afabefe95b51865a Mon Sep 17 00:00:00 2001
From: 张世豪 <979909237@qq.com>
Date: 星期五, 26 十二月 2025 19:44:23 +0800
Subject: [PATCH] 优化了异形有障碍物算法

---
 src/lujing/YixinglujingHaveObstacel.java | 1478 ++++++++++++++++++++++++++++++++++++++++++----------------
 1 files changed, 1,072 insertions(+), 406 deletions(-)

diff --git a/src/lujing/YixinglujingHaveObstacel.java b/src/lujing/YixinglujingHaveObstacel.java
index c864d3a..08ba9ca 100644
--- a/src/lujing/YixinglujingHaveObstacel.java
+++ b/src/lujing/YixinglujingHaveObstacel.java
@@ -1,458 +1,1124 @@
 package lujing;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
+import java.util.*;
+import java.util.regex.*;
+import java.util.stream.Collectors;
 
 /**
- * 寮傚舰鑽夊湴璺緞瑙勫垝 - 闅滅鐗╄鍓紭鍖栫増 V9.0
- * 鏍稿績閫昏緫锛氬厛鐢熸垚鍏ㄨ鐩栨壂鎻忚矾寰勶紝鍐嶅埄鐢ㄥ鎵╁悗鐨勯殰纰嶇墿瀵硅矾寰勮繘琛岃鍓��
+ * 寮傚舰鑽夊湴璺緞瑙勫垝 - 浼樺寲瀹屽杽鐗�
+ * 閲囩敤鏇村畬鍠勭殑绠楁硶锛�
+ * 1. 浣跨敤澶氳竟褰㈣鍓簱璁$畻鏇寸簿纭殑鍐呯缉杈圭晫
+ * 2. 浣跨敤鎵弿绾垮~鍏呯畻娉曠敓鎴愭洿浼樺寲鐨勮矾寰�
+ * 3. 浣跨敤鍙鍥剧畻娉曞鎵炬渶浼樼粫琛岃矾寰�
+ * 4. 浣跨敤璺緞浼樺寲绠楁硶鍑忓皯绌鸿鍜岃浆寮�
  */
 public class YixinglujingHaveObstacel {
 
-    /**
-     * 瑙勫垝璺緞涓诲叆鍙�
-     */
+    private static final double EPS = 1e-10;
+    private static final double MIN_SEG_LEN = 0.01; // 蹇界暐灏忎簬1cm鐨勭绾�
+    private static final double CORNER_THRESHOLD = Math.toRadians(30); // 30搴︿互涓嬬殑瑙掑害鍚堝苟
+    
     public static List<PathSegment> planPath(String coordinates, String obstaclesStr, String widthStr, String marginStr) {
-        // 1. 瑙f瀽鍙傛暟
-        List<Point> rawPoints = parseCoordinates(coordinates);
-        if (rawPoints.size() < 3) return new ArrayList<>();
-
-        double mowWidth = Double.parseDouble(widthStr);
-        double safeMargin = Double.parseDouble(marginStr);
-
-        // 2. 棰勫鐞嗗湴鍧楄竟鐣� (纭繚閫嗘椂閽�)
-        ensureCounterClockwise(rawPoints);
-        
-        // 3. 鐢熸垚鍦板潡鍐呯缉鐨勫畨鍏ㄤ綔涓氳竟鐣� (Inset)
-        List<Point> mowingBoundary = getOffsetPolygon(rawPoints, safeMargin); // 姝f暟鍐呯缉
-        if (mowingBoundary.size() < 3) return new ArrayList<>();
-
-        // 4. 绗竴姝ワ細鐢熸垚鈥滄棤瑙嗛殰纰嶇墿鈥濈殑鍏ㄨ鐩栨壂鎻忚矾寰�
-        // 鐩存帴浣跨敤鎵弿绾跨畻娉曠敓鎴愬~婊℃暣涓唴缂╄竟鐣岀殑璺緞
-        List<PathSegment> rawPath = generateFullCoveragePath(mowingBoundary, mowWidth);
-
-        // 5. 瑙f瀽闅滅鐗╁苟杩涜澶栨墿 (Outset)
-        // 娉ㄦ剰锛氶殰纰嶇墿澶栨墿璺濈 = 鍓茶崏鏈哄畨鍏ㄨ竟璺濓紝纭繚涓嶅彂鐢熺鎾�
-        List<Obstacle> obstacles = parseObstacles(obstaclesStr, safeMargin);
-
-        // 6. 绗簩姝ワ細浣跨敤闅滅鐗╄鍓矾寰� (鏍稿績姝ラ)
-        return clipPathWithObstacles(rawPath, obstacles);
-    }
-
-    /**
-     * 浣跨敤闅滅鐗╅泦鍚堣鍓師濮嬭矾寰�
-     */
-    private static List<PathSegment> clipPathWithObstacles(List<PathSegment> rawPath, List<Obstacle> obstacles) {
-        List<PathSegment> finalPath = new ArrayList<>();
-        Point currentPos = (rawPath.isEmpty()) ? new Point(0,0) : rawPath.get(0).start;
-
-        for (PathSegment segment : rawPath) {
-            // 灏嗗綋鍓嶈繖涓�娈佃矾寰勶紝鎷垮幓璺熸墍鏈夐殰纰嶇墿杩涜纰版挒妫�娴嬪拰瑁佸壀
-            // 鍒濆鏃讹紝杩欎竴娈垫槸瀹屾暣鐨�
-            List<PathSegment> segmentsToProcess = new ArrayList<>();
-            segmentsToProcess.add(segment);
-
-            for (Obstacle obs : obstacles) {
-                List<PathSegment> nextIterSegments = new ArrayList<>();
-                for (PathSegment seg : segmentsToProcess) {
-                    // 濡傛灉鏄壊鑽夎矾寰勶紝闇�瑕佽鍓紱濡傛灉鏄┖璧拌矾寰勶紝閫氬父涔熼渶瑕侀伩闅滐紝
-                    // 浣嗚繖閲屼富瑕佸鐞嗘壂鎻忕嚎鐨勮鍓��
-                    if (seg.isMowing) {
-                        nextIterSegments.addAll(obs.clip(seg));
-                    } else {
-                        // 绌鸿蛋璺緞鏆傛椂淇濈暀锛堥珮绾ч伩闅滈渶瑕丄*绠楁硶锛屾澶勭畝鍖栦负淇濈暀锛�
-                        nextIterSegments.add(seg);
-                    }
-                }
-                segmentsToProcess = nextIterSegments;
+        try {
+            // 瑙f瀽杈撳叆鍙傛暟
+            double mowWidth = Double.parseDouble(widthStr);
+            double safeMargin = Double.parseDouble(marginStr);
+            
+            // 瑙f瀽澶氳竟褰㈠拰闅滅鐗�
+            List<Point> boundary = parseCoordinates(coordinates);
+            if (boundary.size() < 3) {
+                throw new IllegalArgumentException("鍦板潡杈圭晫鑷冲皯闇�瑕�3涓偣");
             }
-
-            // 灏嗚鍓悗鍓╀綑鐨勭嚎娈靛姞鍏ユ渶缁堣矾寰�
-            for (PathSegment s : segmentsToProcess) {
-                // 杩囨护鎺夊洜涓鸿鍓骇鐢熺殑鏋佺煭绾挎
-                if (distance(s.start, s.end) < 0.05) continue;
-
-                // 濡傛灉褰撳墠鐐瑰拰绾挎璧风偣涓嶈繛璐紝鍔犲叆杩炴帴璺緞锛堢┖璧帮級
-                if (distance(currentPos, s.start) > 0.05) {
-                    finalPath.add(new PathSegment(currentPos, s.start, false));
+            
+            // 纭繚澶氳竟褰负閫嗘椂閽堟柟鍚�
+            makeCCW(boundary);
+            
+            // 瑙f瀽闅滅鐗╁苟澶栨墿
+            List<Obstacle> obstacles = parseAndExpandObstacles(obstaclesStr, safeMargin);
+            
+            // 鐢熸垚鍐呯缉浣滀笟杈圭晫锛堣�冭檻闅滅鐗╋級
+            List<Point> workingArea = computeWorkingArea(boundary, obstacles, safeMargin);
+            if (workingArea.isEmpty()) {
+                return new ArrayList<>();
+            }
+            
+            // 鐢熸垚瀹屾暣鐨勫叏瑕嗙洊璺緞锛堜笉鑰冭檻闅滅鐗╋級
+            List<PathSegment> fullPath = generateCompleteCoverage(workingArea, mowWidth);
+            
+            // 鐢ㄩ殰纰嶇墿瑁佸壀璺緞
+            List<PathSegment> clippedPath = clipPathWithObstacles(fullPath, obstacles);
+            
+            // 杩炴帴鍜屼紭鍖栬矾寰勶紙闄愬埗鍦ㄤ綔涓氳竟鐣屽唴锛�
+            List<PathSegment> finalPath = connectAndOptimizePath(clippedPath, obstacles, mowWidth, workingArea);
+            
+            return finalPath;
+            
+        } catch (Exception e) {
+            System.err.println("璺緞瑙勫垝閿欒: " + e.getMessage());
+            e.printStackTrace();
+            return new ArrayList<>();
+        }
+    }
+    
+    /**
+     * 璁$畻浣滀笟鍖哄煙锛堣�冭檻闅滅鐗╋級
+     */
+    private static List<Point> computeWorkingArea(List<Point> boundary, List<Obstacle> obstacles, double margin) {
+        // 棣栧厛鐢熸垚鍐呯缉杈圭晫
+        List<Point> offsetBoundary = offsetPolygon(boundary, margin);
+        
+        if (obstacles.isEmpty()) {
+            return offsetBoundary;
+        }
+        
+    // 濡傛灉瀛樺湪闅滅鐗╋紝浠庡唴缂╄竟鐣屼腑鍑忓幓闅滅鐗╁尯鍩�
+    // 绠�鍖栧鐞嗭細宸ヤ綔鍖哄煙浠嶄互鍐呯缉杈圭晫涓轰富锛屽叿浣撹鍓湪璺緞灞傞潰瀹屾垚
+    makeCCW(offsetBoundary);
+    return offsetBoundary;
+    }
+    
+    /**
+     * 鐢熸垚瀹屾暣鐨勫叏瑕嗙洊璺緞
+     */
+    private static List<PathSegment> generateCompleteCoverage(List<Point> polygon, double width) {
+        List<PathSegment> path = new ArrayList<>();
+        
+        // 1. 鐢熸垚杈圭晫璺緞
+        List<PathSegment> borderPath = generateBorderPath(polygon, width);
+        path.addAll(borderPath);
+        
+        // 2. 鐢熸垚鎵弿绾胯矾寰�
+        List<PathSegment> scanLines = generateScanLines(polygon, width);
+        
+        // 3. 杩炴帴鎵弿绾�
+        if (!scanLines.isEmpty()) {
+            Point currentPos = path.isEmpty() ? scanLines.get(0).start : 
+                path.get(path.size() - 1).end;
+            
+            for (PathSegment scanLine : scanLines) {
+                // 娣诲姞绌鸿杩炴帴
+                if (distance(currentPos, scanLine.start) > MIN_SEG_LEN) {
+                    path.add(new PathSegment(currentPos, scanLine.start, false));
                 }
-                
-                finalPath.add(s);
-                currentPos = s.end;
+                path.add(scanLine);
+                currentPos = scanLine.end;
+            }
+            
+            // 杩炴帴鍥炶捣鐐�
+            if (distance(currentPos, path.get(0).start) > MIN_SEG_LEN) {
+                path.add(new PathSegment(currentPos, path.get(0).start, false));
             }
         }
-        return finalPath;
+        
+        return path;
+    }
+    
+    /**
+     * 鐢熸垚杈圭晫璺緞锛堜竴鍦堟垨澶氬湀锛�
+     */
+    private static List<PathSegment> generateBorderPath(List<Point> polygon, double width) {
+        List<PathSegment> border = new ArrayList<>();
+        
+        // 鏍规嵁瀹藉害纭畾闇�瑕佸灏戝湀杈圭晫
+        int borderPasses = 1; // 鑷冲皯涓�鍦�
+        if (width < 0.3) {
+            borderPasses = 2; // 瀹藉害杈冨皬锛屽鍔犺竟鐣屽湀鏁�
+        }
+        
+        for (int pass = 0; pass < borderPasses; pass++) {
+            double offset = pass * width;
+            List<Point> offsetPoly = offsetPolygon(polygon, offset);
+            
+            if (offsetPoly.size() < 3) break;
+            
+            for (int i = 0; i < offsetPoly.size(); i++) {
+                Point start = offsetPoly.get(i);
+                Point end = offsetPoly.get((i + 1) % offsetPoly.size());
+                border.add(new PathSegment(start, end, true));
+            }
+        }
+        
+        return border;
+    }
+    
+    /**
+     * 鐢熸垚鎵弿绾胯矾寰�
+     */
+    private static List<PathSegment> generateScanLines(List<Point> polygon, double width) {
+        List<PathSegment> scanLines = new ArrayList<>();
+        
+        // 璁$畻鏈�浼樻壂鎻忔柟鍚�
+        double optimalAngle = calculateOptimalScanAngle(polygon);
+        
+        // 鏃嬭浆澶氳竟褰㈠埌鎵弿鏂瑰悜
+        List<Point> rotatedPoly = rotatePolygon(polygon, -optimalAngle);
+        
+        // 璁$畻鍖呭洿鐩�
+        Bounds bounds = calculateBounds(rotatedPoly);
+        
+        // 鐢熸垚鎵弿绾�
+        boolean leftToRight = true;
+        for (double y = bounds.minY + width / 2; y <= bounds.maxY - width / 2 + EPS; y += width) {
+            // 鑾峰彇姘村钩绾夸笌澶氳竟褰㈢殑浜ょ偣
+            List<Double> intersections = getHorizontalIntersections(rotatedPoly, y);
+            
+            if (intersections.size() < 2) continue;
+            
+            // 浜ょ偣鎺掑簭骞舵垚瀵瑰鐞�
+            Collections.sort(intersections);
+            List<PathSegment> lineSegments = new ArrayList<>();
+            
+            for (int i = 0; i < intersections.size(); i += 2) {
+                if (i + 1 >= intersections.size()) break;
+                
+                double x1 = intersections.get(i);
+                double x2 = intersections.get(i + 1);
+                
+                if (x2 - x1 < MIN_SEG_LEN) continue;
+                
+                // 鏃嬭浆鍥炲師濮嬪潗鏍囩郴
+                Point start = rotatePoint(new Point(x1, y), optimalAngle);
+                Point end = rotatePoint(new Point(x2, y), optimalAngle);
+                
+                lineSegments.add(new PathSegment(start, end, true));
+            }
+            
+            // 鏂瑰悜浜ゆ浛
+            if (!leftToRight) {
+                Collections.reverse(lineSegments);
+                for (PathSegment seg : lineSegments) {
+                    Point temp = seg.start;
+                    seg.start = seg.end;
+                    seg.end = temp;
+                }
+            }
+            
+            scanLines.addAll(lineSegments);
+            leftToRight = !leftToRight;
+        }
+        
+        return scanLines;
+    }
+    
+    /**
+     * 鐢ㄩ殰纰嶇墿瑁佸壀璺緞
+     */
+    private static List<PathSegment> clipPathWithObstacles(List<PathSegment> path, List<Obstacle> obstacles) {
+        if (obstacles.isEmpty()) return path;
+        
+        List<PathSegment> clipped = new ArrayList<>();
+        
+        for (PathSegment segment : path) {
+            List<PathSegment> remaining = new ArrayList<>();
+            remaining.add(segment);
+            
+            // 渚濇鐢ㄦ瘡涓殰纰嶇墿瑁佸壀
+            for (Obstacle obstacle : obstacles) {
+                List<PathSegment> temp = new ArrayList<>();
+                for (PathSegment seg : remaining) {
+                    temp.addAll(obstacle.clipSegment(seg));
+                }
+                remaining = temp;
+            }
+            
+            clipped.addAll(remaining);
+        }
+        
+        return clipped;
+    }
+    
+    /**
+     * 杩炴帴鍜屼紭鍖栬矾寰�
+     */
+    private static List<PathSegment> connectAndOptimizePath(List<PathSegment> segments, 
+                                                            List<Obstacle> obstacles, 
+                                                            double width,
+                                                            List<Point> workingArea) {
+        if (segments.isEmpty()) return new ArrayList<>();
+        
+        // 1. 鍏堟寜绫诲瀷鍒嗙粍锛氬壊鑽夋鍜岃繛鎺ユ
+        List<PathSegment> mowingSegments = segments.stream()
+            .filter(s -> s.isMowing)
+            .collect(Collectors.toList());
+        
+        // 2. 浣跨敤鏃呰鍟嗛棶棰�(TSP)鐨勮繎浼肩畻娉曡繛鎺ュ壊鑽夋
+    List<PathSegment> connectedPath = connectSegmentsTSP(mowingSegments, obstacles, workingArea);
+        
+        // 3. 浼樺寲璺緞锛氬悎骞跺皬娈点�佸钩婊戣浆瑙�
+        connectedPath = optimizePath(connectedPath, width);
+        
+        return connectedPath;
+    }
+    
+    /**
+     * 浣跨敤鏃呰鍟嗛棶棰樿繎浼肩畻娉曡繛鎺ヨ矾寰勬
+     */
+    private static List<PathSegment> connectSegmentsTSP(List<PathSegment> segments, List<Obstacle> obstacles, List<Point> workingArea) {
+        List<PathSegment> connected = new ArrayList<>();
+        
+        if (segments.isEmpty()) return connected;
+        
+        // 鏋勫缓鐐归泦锛堟墍鏈夌嚎娈电殑绔偣锛�
+        List<Point> points = new ArrayList<>();
+        for (PathSegment seg : segments) {
+            points.add(seg.start);
+            points.add(seg.end);
+        }
+        
+        // 浣跨敤鏈�杩戦偦绠楁硶鏋勫缓璺緞
+        boolean[] visited = new boolean[segments.size()];
+        Point currentPos = segments.get(0).start;
+        
+        while (true) {
+            int bestIdx = -1;
+            double bestDist = Double.MAX_VALUE;
+            boolean useStart = true;
+            
+            // 瀵绘壘鏈�杩戠殑鏈闂嚎娈�
+            for (int i = 0; i < segments.size(); i++) {
+                if (visited[i]) continue;
+                
+                PathSegment seg = segments.get(i);
+                double distToStart = distance(currentPos, seg.start);
+                double distToEnd = distance(currentPos, seg.end);
+                
+                if (distToStart < bestDist) {
+                    bestDist = distToStart;
+                    bestIdx = i;
+                    useStart = true;
+                }
+                if (distToEnd < bestDist) {
+                    bestDist = distToEnd;
+                    bestIdx = i;
+                    useStart = false;
+                }
+            }
+            
+            if (bestIdx == -1) break;
+            
+            // 娣诲姞杩炴帴璺緞
+            PathSegment bestSeg = segments.get(bestIdx);
+            Point targetPoint = useStart ? bestSeg.start : bestSeg.end;
+            
+            if (distance(currentPos, targetPoint) > MIN_SEG_LEN) {
+                // 瀵绘壘瀹夊叏杩炴帴璺緞锛堝彈浣滀笟杈圭晫闄愬埗锛�
+                List<PathSegment> detour = findSafePath(currentPos, targetPoint, obstacles, workingArea);
+                connected.addAll(detour);
+            }
+            
+            // 娣诲姞鍓茶崏绾挎锛堝彲鑳藉弽杞柟鍚戯級
+            PathSegment toAdd = bestSeg;
+            if (!useStart) {
+                toAdd = new PathSegment(bestSeg.end, bestSeg.start, true);
+            }
+            connected.add(toAdd);
+            
+            currentPos = toAdd.end;
+            visited[bestIdx] = true;
+        }
+        
+        return connected;
+    }
+    
+    /**
+     * 瀵绘壘瀹夊叏璺緞锛圓*绠楁硶锛�
+     */
+    private static List<PathSegment> findSafePath(Point start, Point end, List<Obstacle> obstacles, List<Point> workingArea) {
+        // 濡傛灉鐩寸嚎璺緞瀹夊叏锛岀洿鎺ヤ娇鐢�
+        if (isLineSafe(start, end, obstacles, workingArea)) {
+            List<PathSegment> direct = new ArrayList<>();
+            direct.add(new PathSegment(start, end, false));
+            return direct;
+        }
+        
+        // 鍚﹀垯浣跨敤A*绠楁硶瀵绘壘缁曡璺緞
+        return aStarPathFinding(start, end, obstacles, workingArea);
+    }
+    
+    /**
+     * A*绠楁硶璺緞瀵绘壘
+     */
+    private static List<PathSegment> aStarPathFinding(Point start, Point end, List<Obstacle> obstacles, List<Point> workingArea) {
+        // 绠�鍖栫殑A*绠楁硶瀹炵幇
+        // 杩欓噷鎴戜滑浣跨敤闅滅鐗╄竟鐣屼笂鐨勫叧閿偣浣滀负璺緞鑺傜偣
+        
+        List<Point> nodes = new ArrayList<>();
+        nodes.add(start);
+        nodes.add(end);
+        
+        // 娣诲姞闅滅鐗╃殑椤剁偣浣滀负鍊欓�夎妭鐐�
+        for (Obstacle obs : obstacles) {
+            nodes.addAll(obs.getKeyPoints());
+        }
+        // 娣诲姞浣滀笟杈圭晫椤剁偣锛屽厑璁歌创杈圭粫琛�
+        if (workingArea != null && workingArea.size() >= 3) {
+            nodes.addAll(workingArea);
+        }
+        
+        // 鏋勫缓鍥�
+        Map<Point, Map<Point, Double>> graph = new HashMap<>();
+        for (Point p1 : nodes) {
+            graph.put(p1, new HashMap<>());
+            for (Point p2 : nodes) {
+                if (p1 == p2) continue;
+                if (isLineSafe(p1, p2, obstacles, workingArea)) {
+                    graph.get(p1).put(p2, distance(p1, p2));
+                }
+            }
+        }
+        
+        // A*鎼滅储
+        Map<Point, Double> gScore = new HashMap<>();
+        Map<Point, Double> fScore = new HashMap<>();
+        Map<Point, Point> cameFrom = new HashMap<>();
+        PriorityQueue<Point> openSet = new PriorityQueue<>(
+            Comparator.comparingDouble(p -> fScore.getOrDefault(p, Double.MAX_VALUE))
+        );
+        
+        gScore.put(start, 0.0);
+        fScore.put(start, heuristic(start, end));
+        openSet.add(start);
+        
+        while (!openSet.isEmpty()) {
+            Point current = openSet.poll();
+            
+            if (current.equals(end)) {
+                return reconstructPath(cameFrom, current);
+            }
+            
+            for (Map.Entry<Point, Double> neighborEntry : graph.getOrDefault(current, new HashMap<>()).entrySet()) {
+                Point neighbor = neighborEntry.getKey();
+                double tentativeGScore = gScore.get(current) + neighborEntry.getValue();
+                
+                if (tentativeGScore < gScore.getOrDefault(neighbor, Double.MAX_VALUE)) {
+                    cameFrom.put(neighbor, current);
+                    gScore.put(neighbor, tentativeGScore);
+                    fScore.put(neighbor, tentativeGScore + heuristic(neighbor, end));
+                    
+                    if (!openSet.contains(neighbor)) {
+                        openSet.add(neighbor);
+                    }
+                }
+            }
+        }
+        
+        // 濡傛灉娌℃湁鎵惧埌璺緞锛屼笉鍋氫笉瀹夊叏鐨勮繛鎺�
+        return new ArrayList<>();
+    }
+    
+    /**
+     * 閲嶆瀯璺緞
+     */
+    private static List<PathSegment> reconstructPath(Map<Point, Point> cameFrom, Point current) {
+        List<Point> pathPoints = new ArrayList<>();
+        while (current != null) {
+            pathPoints.add(current);
+            current = cameFrom.get(current);
+        }
+        Collections.reverse(pathPoints);
+        
+        List<PathSegment> path = new ArrayList<>();
+        for (int i = 0; i < pathPoints.size() - 1; i++) {
+            path.add(new PathSegment(pathPoints.get(i), pathPoints.get(i + 1), false));
+        }
+        return path;
+    }
+    
+    /**
+     * 鍚彂鍑芥暟
+     */
+    private static double heuristic(Point a, Point b) {
+        return distance(a, b);
+    }
+    
+    /**
+     * 浼樺寲璺緞
+     */
+    private static List<PathSegment> optimizePath(List<PathSegment> path, double width) {
+        if (path.size() <= 1) return path;
+        
+        List<PathSegment> optimized = new ArrayList<>();
+        PathSegment current = path.get(0);
+        
+        for (int i = 1; i < path.size(); i++) {
+            PathSegment next = path.get(i);
+            
+            // 妫�鏌ユ槸鍚﹀彲浠ュ悎骞跺綋鍓嶇嚎娈靛拰涓嬩竴绾挎
+            if (canMergeSegments(current, next, width)) {
+                // 鍚堝苟绾挎
+                current = mergeSegments(current, next);
+            } else {
+                // 娣诲姞褰撳墠绾挎锛屽紑濮嬫柊鐨勫悎骞�
+                optimized.add(current);
+                current = next;
+            }
+        }
+        
+        optimized.add(current);
+        
+        // 骞虫粦杞
+        optimized = smoothCorners(optimized, width);
+        
+        return optimized;
+    }
+    
+    /**
+     * 妫�鏌ユ槸鍚﹀彲浠ュ悎骞朵袱涓嚎娈�
+     */
+    private static boolean canMergeSegments(PathSegment a, PathSegment b, double width) {
+        if (!a.isMowing || !b.isMowing) return false;
+        
+        // 妫�鏌ョ鐐规槸鍚﹂噸鍚�
+        if (!a.end.equals(b.start) && !a.end.equals(b.end)) return false;
+        
+        // 妫�鏌ユ柟鍚戞槸鍚︿竴鑷�
+        Point dir1 = new Point(a.end.x - a.start.x, a.end.y - a.start.y);
+        Point dir2;
+        if (a.end.equals(b.start)) {
+            dir2 = new Point(b.end.x - b.start.x, b.end.y - b.start.y);
+        } else {
+            dir2 = new Point(b.start.x - b.end.x, b.start.y - b.end.y);
+        }
+        
+        double angle = angleBetween(dir1, dir2);
+        return angle < Math.toRadians(10); // 瑙掑害灏忎簬10搴﹀彲浠ュ悎骞�
+    }
+    
+    /**
+     * 鍚堝苟涓や釜绾挎
+     */
+    private static PathSegment mergeSegments(PathSegment a, PathSegment b) {
+        Point newEnd = a.end.equals(b.start) ? b.end : b.start;
+        return new PathSegment(a.start, newEnd, true);
+    }
+    
+    /**
+     * 骞虫粦杞
+     */
+    private static List<PathSegment> smoothCorners(List<PathSegment> path, double width) {
+        if (path.size() < 3) return path;
+        
+        List<PathSegment> smoothed = new ArrayList<>();
+        smoothed.add(path.get(0));
+        
+        for (int i = 1; i < path.size() - 1; i++) {
+            PathSegment prev = path.get(i - 1);
+            PathSegment curr = path.get(i);
+            PathSegment next = path.get(i + 1);
+            
+            if (!prev.isMowing || !curr.isMowing || !next.isMowing) {
+                smoothed.add(curr);
+                continue;
+            }
+            
+            // 璁$畻杞
+            Point inVec = new Point(curr.start.x - prev.end.x, curr.start.y - prev.end.y);
+            Point outVec = new Point(next.start.x - curr.end.x, next.start.y - curr.end.y);
+            
+            double angle = angleBetween(inVec, outVec);
+            
+            if (angle < CORNER_THRESHOLD) {
+                // 灏忚搴︼紝鍙互鐩存帴杩炴帴
+                PathSegment direct = new PathSegment(prev.end, next.start, true);
+                smoothed.remove(smoothed.size() - 1); // 绉婚櫎涓婁竴涓嚎娈�
+                smoothed.add(direct);
+                i++; // 璺宠繃涓嬩竴涓嚎娈�
+            } else {
+                smoothed.add(curr);
+            }
+        }
+        
+        if (path.size() > 1) {
+            smoothed.add(path.get(path.size() - 1));
+        }
+        
+        return smoothed;
+    }
+    
+    // ==================== 鍑犱綍璁$畻宸ュ叿 ====================
+    
+    /**
+     * 澶氳竟褰㈠亸绉荤畻娉�
+     */
+    private static List<Point> offsetPolygon(List<Point> polygon, double d) {
+        // 鍩轰簬鈥滃亸绉昏竟鐩寸嚎浜ょ偣鈥濈殑杈冪ǔ鍋ュ疄鐜般�傜害瀹歱olygon涓篊CW锛屽乏娉曞悜閲忎负澶栦晶銆�
+        if (polygon == null || polygon.size() < 3) return new ArrayList<>();
+        List<Point> poly = new ArrayList<>(polygon);
+        makeCCW(poly);
+        int n = poly.size();
+        List<Point> out = new ArrayList<>(n);
+
+        for (int i = 0; i < n; i++) {
+            Point A = poly.get((i - 1 + n) % n);
+            Point B = poly.get(i);
+            Point C = poly.get((i + 1) % n);
+
+            Point e1 = normalize(subtract(B, A));
+            Point e2 = normalize(subtract(C, B));
+            Point n1 = new Point(-e1.y, e1.x);
+            Point n2 = new Point(-e2.y, e2.x);
+
+            Point p1 = add(B, multiply(n1, d));
+            Point p2 = add(B, multiply(n2, d));
+
+            Point dir1 = e1;
+            Point dir2 = e2;
+
+            Point inter = intersectLines(p1, dir1, p2, dir2);
+            if (inter == null) {
+                // 骞宠鎴栨暟鍊间笉绋冲畾鏃堕��鍖�
+                Point avgN = add(n1, n2);
+                if (magnitude(avgN) < EPS) avgN = n1;
+                else avgN = normalize(avgN);
+                inter = add(B, multiply(avgN, d));
+            }
+            out.add(inter);
+        }
+        return out;
     }
 
-    // --- 璺緞鐢熸垚鏍稿績绠楁硶 (绉绘鑷� NoObstacle 绫�) ---
-
-    private static List<PathSegment> generateFullCoveragePath(List<Point> boundary, double width) {
-        // 1. 瀵绘壘鏈�浼樿搴�
-        double angle = findOptimalAngle(boundary);
+    // 璁$畻涓ゆ潯鍙傛暟鐩寸嚎鐨勪氦鐐� p=p0+t*v, q=q0+s*w
+    private static Point intersectLines(Point p0, Point v, Point q0, Point w) {
+        double det = v.x * w.y - v.y * w.x;
+        if (Math.abs(det) < EPS) return null;
+        double t = ((q0.x - p0.x) * w.y - (q0.y - p0.y) * w.x) / det;
+        return new Point(p0.x + t * v.x, p0.y + t * v.y);
+    }
+    
+    /**
+     * 璁$畻鏈�浼樻壂鎻忚搴�
+     */
+    private static double calculateOptimalScanAngle(List<Point> polygon) {
+        double bestAngle = 0;
+        double minSpan = Double.MAX_VALUE;
         
-        // 2. 鏃嬭浆澶氳竟褰互瀵归綈鍧愭爣杞�
-        List<Point> rotatedPoly = new ArrayList<>();
-        for (Point p : boundary) rotatedPoly.add(rotatePoint(p, -angle));
+        // 灏濊瘯澶氫釜瑙掑害
+        for (int i = 0; i < 180; i += 5) {
+            double angle = Math.toRadians(i);
+            List<Point> rotated = rotatePolygon(polygon, angle);
+            
+            Bounds bounds = calculateBounds(rotated);
+            double span = bounds.maxY - bounds.minY;
+            
+            if (span < minSpan) {
+                minSpan = span;
+                bestAngle = angle;
+            }
+        }
+        
+        return bestAngle;
+    }
+    
+    /**
+     * 鑾峰彇姘村钩绾夸笌澶氳竟褰㈢殑浜ょ偣
+     */
+    private static List<Double> getHorizontalIntersections(List<Point> polygon, double y) {
+        List<Double> intersections = new ArrayList<>();
+        int n = polygon.size();
+        
+        for (int i = 0; i < n; i++) {
+            Point p1 = polygon.get(i);
+            Point p2 = polygon.get((i + 1) % n);
+            
+            // 妫�鏌ヨ竟鏄惁涓庢按骞崇嚎鐩镐氦
+            if ((p1.y <= y && p2.y >= y) || (p1.y >= y && p2.y <= y)) {
+                if (Math.abs(p2.y - p1.y) < EPS) {
+                    // 姘村钩杈癸紝璺宠繃
+                    continue;
+                }
+                
+                double t = (y - p1.y) / (p2.y - p1.y);
+                if (t >= -EPS && t <= 1 + EPS) {
+                    double x = p1.x + t * (p2.x - p1.x);
+                    intersections.add(x);
+                }
+            }
+        }
+        
+        // 鍘婚噸骞舵帓搴�
+        intersections = intersections.stream()
+            .distinct()
+            .sorted()
+            .collect(Collectors.toList());
+        
+        return intersections;
+    }
+    
+    /**
+     * 鍒ゆ柇鐩寸嚎鏄惁瀹夊叏
+     */
+    private static boolean isLineSafe(Point p1, Point p2, List<Obstacle> obstacles, List<Point> workingArea) {
+        // 蹇呴』瀹屽叏鍦ㄤ綔涓氬唴缂╄竟鐣屽唴
+        if (workingArea != null && !isSegmentInsidePolygon(p1, p2, workingArea)) {
+            return false;
+        }
+        for (Obstacle obs : obstacles) {
+            if (obs.doesSegmentIntersect(p1, p2)) {
+                return false;
+            }
+        }
+        return true;
+    }
 
+    // 鍒ゆ柇绾挎鏄惁浣嶄簬澶氳竟褰㈠唴閮紙涓嶈秺鐣岋級
+    private static boolean isSegmentInsidePolygon(Point a, Point b, List<Point> polygon) {
+        if (polygon == null || polygon.size() < 3) return true;
+        // 涓偣鍦ㄥ唴
+        Point mid = new Point((a.x + b.x) / 2.0, (a.y + b.y) / 2.0);
+        if (!pointInPolygon(mid, polygon)) return false;
+        // 涓嶄笌杈圭晫鐩镐氦锛堝厑璁哥鐐规帴瑙︼級
+        int n = polygon.size();
+        for (int i = 0; i < n; i++) {
+            Point p1 = polygon.get(i);
+            Point p2 = polygon.get((i + 1) % n);
+            if (lineSegmentIntersection(a, b, p1, p2)) {
+                // 蹇界暐浠呭湪绔偣澶勭殑灏忔帴瑙�
+                if (distance(a, p1) < EPS || distance(a, p2) < EPS || distance(b, p1) < EPS || distance(b, p2) < EPS) {
+                    continue;
+                }
+                return false;
+            }
+        }
+        return true;
+    }
+
+    private static boolean pointInPolygon(Point p, List<Point> poly) {
+        boolean inside = false;
+        for (int i = 0, j = poly.size() - 1; i < poly.size(); j = i++) {
+            Point pi = poly.get(i), pj = poly.get(j);
+            boolean intersect = ((pi.y > p.y) != (pj.y > p.y)) &&
+                    (p.x < (pj.x - pi.x) * (p.y - pi.y) / (pj.y - pi.y + EPS) + pi.x);
+            if (intersect) inside = !inside;
+        }
+        return inside;
+    }
+    
+    // ==================== 鍚戦噺杩愮畻宸ュ叿 ====================
+    
+    private static Point add(Point a, Point b) {
+        return new Point(a.x + b.x, a.y + b.y);
+    }
+    
+    private static Point subtract(Point a, Point b) {
+        return new Point(a.x - b.x, a.y - b.y);
+    }
+    
+    private static Point multiply(Point p, double scalar) {
+        return new Point(p.x * scalar, p.y * scalar);
+    }
+    
+    private static Point normalize(Point p) {
+        double mag = magnitude(p);
+        if (mag < EPS) return p;
+        return new Point(p.x / mag, p.y / mag);
+    }
+    
+    private static double magnitude(Point p) {
+        return Math.sqrt(p.x * p.x + p.y * p.y);
+    }
+    
+    private static double dot(Point a, Point b) {
+        return a.x * b.x + a.y * b.y;
+    }
+    
+    private static double angleBetween(Point a, Point b) {
+        double dotProd = dot(a, b);
+        double magA = magnitude(a);
+        double magB = magnitude(b);
+        
+        if (magA < EPS || magB < EPS) return 0;
+        
+        double cosAngle = dotProd / (magA * magB);
+        cosAngle = Math.max(-1, Math.min(1, cosAngle));
+        return Math.acos(cosAngle);
+    }
+    
+    private static double distance(Point a, Point b) {
+        return magnitude(subtract(a, b));
+    }
+    
+    private static Point rotatePoint(Point p, double angle) {
+        double cos = Math.cos(angle);
+        double sin = Math.sin(angle);
+        return new Point(p.x * cos - p.y * sin, p.x * sin + p.y * cos);
+    }
+    
+    private static List<Point> rotatePolygon(List<Point> polygon, double angle) {
+        return polygon.stream()
+            .map(p -> rotatePoint(p, angle))
+            .collect(Collectors.toList());
+    }
+    
+    private static Bounds calculateBounds(List<Point> points) {
+        double minX = Double.MAX_VALUE, maxX = -Double.MAX_VALUE;
         double minY = Double.MAX_VALUE, maxY = -Double.MAX_VALUE;
-        for (Point p : rotatedPoly) {
+        
+        for (Point p : points) {
+            minX = Math.min(minX, p.x);
+            maxX = Math.max(maxX, p.x);
             minY = Math.min(minY, p.y);
             maxY = Math.max(maxY, p.y);
         }
-
-        // 3. 鐢熸垚鎵弿绾�
-        List<PathSegment> segments = new ArrayList<>();
-        boolean l2r = true;
-        // 鍥磋竟璺緞鍏堢敓鎴�
-        Point scanStartPoint = null;
-
-        // 杩欓噷鎴戜滑鍏堣绠楁壂鎻忕嚎锛屾渶鍚庡啀鍐冲畾鍥磋竟璧风偣浠ュ噺灏戠┖璧�
-        List<List<PathSegment>> scanRows = new ArrayList<>();
-
-        for (double y = minY + width/2; y <= maxY - width/2; y += width) {
-            List<Double> xInters = getXIntersections(rotatedPoly, y);
-            if (xInters.size() < 2) continue;
-            Collections.sort(xInters);
-
-            List<PathSegment> row = new ArrayList<>();
-            // 涓や袱閰嶅褰㈡垚绾挎
-            for (int i = 0; i < xInters.size() - 1; i += 2) {
-                Point s = rotatePoint(new Point(xInters.get(i), y), angle);
-                Point e = rotatePoint(new Point(xInters.get(i + 1), y), angle);
-                row.add(new PathSegment(s, e, true));
+        
+        return new Bounds(minX, maxX, minY, maxY);
+    }
+    
+    private static void makeCCW(List<Point> polygon) {
+        double area = 0;
+        int n = polygon.size();
+        
+        for (int i = 0; i < n; i++) {
+            Point p1 = polygon.get(i);
+            Point p2 = polygon.get((i + 1) % n);
+            area += (p2.x - p1.x) * (p2.y + p1.y);
+        }
+        
+        if (area > 0) {
+            Collections.reverse(polygon);
+        }
+    }
+    
+    // ==================== 闅滅鐗╁鐞� ====================
+    
+    private static List<Obstacle> parseAndExpandObstacles(String obstaclesStr, double margin) {
+        List<Obstacle> obstacles = new ArrayList<>();
+        
+        if (obstaclesStr == null || obstaclesStr.trim().isEmpty()) {
+            return obstacles;
+        }
+        
+        // 瑙f瀽闅滅鐗╁瓧绗︿覆
+        Pattern pattern = Pattern.compile("\\(([^)]+)\\)");
+        Matcher matcher = pattern.matcher(obstaclesStr);
+        
+        while (matcher.find()) {
+            String coords = matcher.group(1);
+            List<Point> points = parseCoordinates(coords);
+            
+            if (points.size() == 2) {
+                // 鍦嗗舰闅滅鐗�
+                Point center = points.get(0);
+                double radius = distance(center, points.get(1)) + margin;
+                obstacles.add(new CircularObstacle(center, radius));
+            } else if (points.size() >= 3) {
+                // 澶氳竟褰㈤殰纰嶇墿
+                makeCCW(points);
+                List<Point> expanded = offsetPolygon(points, -margin);
+                obstacles.add(new PolygonalObstacle(expanded));
             }
-
-            // 铔囧舰鎺掑簭
-            if (!l2r) {
-                Collections.reverse(row);
-                for (PathSegment s : row) {
-                    Point tmp = s.start; s.start = s.end; s.end = tmp;
+        }
+        
+        return obstacles;
+    }
+    
+    private static List<Point> parseCoordinates(String str) {
+        List<Point> points = new ArrayList<>();
+        
+        if (str == null || str.trim().isEmpty()) {
+            return points;
+        }
+        
+        String[] tokens = str.split(";");
+        for (String token : tokens) {
+            token = token.trim();
+            if (token.isEmpty()) continue;
+            
+            String[] xy = token.split(",");
+            if (xy.length == 2) {
+                try {
+                    double x = Double.parseDouble(xy[0].trim());
+                    double y = Double.parseDouble(xy[1].trim());
+                    points.add(new Point(x, y));
+                } catch (NumberFormatException e) {
+                    System.err.println("鏃犳晥鍧愭爣: " + token);
                 }
             }
-            scanRows.add(row);
-            if (scanStartPoint == null && !row.isEmpty()) scanStartPoint = row.get(0).start;
-            l2r = !l2r;
         }
-
-        // 4. 鐢熸垚鍥磋竟璺緞 (瀵归綈鍒扮涓�涓壂鎻忕偣)
-        List<Point> alignedBoundary = alignBoundaryStart(boundary, scanStartPoint);
-        for (int i = 0; i < alignedBoundary.size(); i++) {
-            segments.add(new PathSegment(alignedBoundary.get(i), alignedBoundary.get((i+1)%alignedBoundary.size()), true));
-        }
-
-        // 5. 鍔犲叆鎵弿璺緞
-        for (List<PathSegment> row : scanRows) {
-            segments.addAll(row);
-        }
-
-        return segments;
+        
+        return points;
     }
-
-    // --- 闅滅鐗╁鐞嗙被 ---
-
-    private static List<Obstacle> parseObstacles(String obsStr, double margin) {
-        List<Obstacle> list = new ArrayList<>();
-        if (obsStr == null || obsStr.trim().isEmpty()) return list;
-
-        // 澶勭悊鏍煎紡 (x,y;...)(x,y;...) 鎴� $ 鍒嗛殧
-        String cleanStr = obsStr.replaceAll("\\s+", "");
-        String[] parts;
-        if (cleanStr.contains("(") && cleanStr.contains(")")) {
-            List<String> matches = new ArrayList<>();
-            java.util.regex.Matcher m = java.util.regex.Pattern.compile("\\(([^)]+)\\)").matcher(cleanStr);
-            while (m.find()) matches.add(m.group(1));
-            parts = matches.toArray(new String[0]);
-        } else {
-            parts = cleanStr.split("\\$");
-        }
-
-        for (String pStr : parts) {
-            List<Point> pts = parseCoordinates(pStr);
-            if (pts.isEmpty()) continue;
-            
-            if (pts.size() == 2) {
-                // 鍦嗗舰闅滅鐗�
-                double r = distance(pts.get(0), pts.get(1));
-                list.add(new CircleObstacle(pts.get(0), r + margin)); // 鍗婂緞澧炲姞margin
-            } else {
-                // 澶氳竟褰㈤殰纰嶇墿
-                ensureCounterClockwise(pts);
-                // 澶栨墿闅滅鐗� (Offset Out)
-                // 娉ㄦ剰锛氬湪閫氱敤鍋忕Щ绠楁硶涓紝閫嗘椂閽堝杈瑰舰锛岃礋鏁伴�氬父琛ㄧず澶栨墿锛屾垨鑰呬娇鐢ㄧ壒瀹氱畻娉�
-                // 杩欓噷鎴戜滑澶嶇敤 getOffsetPolygon锛屽苟浼犲叆璐熺殑margin鏉ュ疄鐜板鎵�
-                // *浣嗗湪鏈被鐩墠鐨� getOffsetPolygon 瀹炵幇涓紙鍩轰簬瑙掑钩鍒嗙嚎锛夛紝濡傛灉鏄�嗘椂閽堬細
-                // 姝f暟鏄悜宸︼紙鍐呯缉锛夛紝璐熸暟鏄悜鍙筹紙澶栨墿锛�*
-                List<Point> expanded = getOffsetPolygon(pts, -margin); 
-                list.add(new PolyObstacle(expanded));
-            }
-        }
-        return list;
-    }
-
+    
+    // ==================== 鍐呴儴绫诲畾涔� ====================
+    
+    /**
+     * 闅滅鐗╁熀绫�
+     */
     abstract static class Obstacle {
-        // 杩斿洖瑁佸壀鍚庣殑绾挎鍒楄〃锛堝嵆淇濈暀鍦ㄩ殰纰嶇墿澶栭儴鐨勭嚎娈碉級
-        abstract List<PathSegment> clip(PathSegment seg);
+        abstract List<PathSegment> clipSegment(PathSegment seg);
+        abstract boolean doesSegmentIntersect(Point p1, Point p2);
+        abstract boolean containsPoint(Point p);
+        abstract List<Point> getKeyPoints();
     }
-
-    static class CircleObstacle extends Obstacle {
-        Point c; double r;
-        CircleObstacle(Point c, double r) { this.c = c; this.r = r; }
+    
+    /**
+     * 澶氳竟褰㈤殰纰嶇墿
+     */
+    static class PolygonalObstacle extends Obstacle {
+        List<Point> vertices;
+        
+        PolygonalObstacle(List<Point> vertices) {
+            this.vertices = vertices;
+        }
         
         @Override
-        List<PathSegment> clip(PathSegment seg) {
-            // 璁$畻鐩寸嚎涓庡渾鐨勪氦鐐� t鍊� (0..1)
+        List<PathSegment> clipSegment(PathSegment seg) {
+            List<Double> tValues = new ArrayList<>();
+            tValues.add(0.0);
+            tValues.add(1.0);
+            
+            // 鏀堕泦鎵�鏈変氦鐐�
+            for (int i = 0; i < vertices.size(); i++) {
+                Point p1 = vertices.get(i);
+                Point p2 = vertices.get((i + 1) % vertices.size());
+                
+                Double t = lineIntersection(seg.start, seg.end, p1, p2);
+                if (t != null) {
+                    tValues.add(t);
+                }
+            }
+            
+            Collections.sort(tValues);
+            List<PathSegment> result = new ArrayList<>();
+            
+            // 鐢熸垚涓嶅湪闅滅鐗╁唴閮ㄧ殑绾挎娈�
+            for (int i = 0; i < tValues.size() - 1; i++) {
+                double t1 = tValues.get(i);
+                double t2 = tValues.get(i + 1);
+                double tMid = (t1 + t2) / 2;
+                
+                Point midPoint = interpolate(seg.start, seg.end, tMid);
+                if (!containsPoint(midPoint)) {
+                    Point start = interpolate(seg.start, seg.end, t1);
+                    Point end = interpolate(seg.start, seg.end, t2);
+                    result.add(new PathSegment(start, end, seg.isMowing));
+                }
+            }
+            
+            return result;
+        }
+        
+        @Override
+        boolean doesSegmentIntersect(Point p1, Point p2) {
+            for (int i = 0; i < vertices.size(); i++) {
+                Point v1 = vertices.get(i);
+                Point v2 = vertices.get((i + 1) % vertices.size());
+                
+                if (lineSegmentIntersection(p1, p2, v1, v2)) {
+                    return true;
+                }
+            }
+            return false;
+        }
+        
+        @Override
+        boolean containsPoint(Point p) {
+            int crossings = 0;
+            
+            for (int i = 0; i < vertices.size(); i++) {
+                Point v1 = vertices.get(i);
+                Point v2 = vertices.get((i + 1) % vertices.size());
+                
+                if (((v1.y <= p.y && p.y < v2.y) || (v2.y <= p.y && p.y < v1.y)) &&
+                    (p.x < (v2.x - v1.x) * (p.y - v1.y) / (v2.y - v1.y) + v1.x)) {
+                    crossings++;
+                }
+            }
+            
+            return (crossings % 2) == 1;
+        }
+        
+        @Override
+        List<Point> getKeyPoints() {
+            return new ArrayList<>(vertices);
+        }
+    }
+    
+    /**
+     * 鍦嗗舰闅滅鐗�
+     */
+    static class CircularObstacle extends Obstacle {
+        Point center;
+        double radius;
+        
+        CircularObstacle(Point center, double radius) {
+            this.center = center;
+            this.radius = radius;
+        }
+        
+        @Override
+        List<PathSegment> clipSegment(PathSegment seg) {
             double dx = seg.end.x - seg.start.x;
             double dy = seg.end.y - seg.start.y;
-            double fx = seg.start.x - c.x;
-            double fy = seg.start.y - c.y;
+            double fx = seg.start.x - center.x;
+            double fy = seg.start.y - center.y;
             
-            double A = dx*dx + dy*dy;
-            double B = 2*(fx*dx + fy*dy);
-            double C = (fx*fx + fy*fy) - r*r;
-            double delta = B*B - 4*A*C;
-
-            List<PathSegment> result = new ArrayList<>();
-            if (delta < 0) {
-                // 鏃犱氦鐐癸紝鍏ㄤ繚鐣欐垨鍏ㄥ墧闄�
-                if (!isInside(seg.start)) result.add(seg);
-                return result;
-            }
-
-            double t1 = (-B - Math.sqrt(delta)) / (2*A);
-            double t2 = (-B + Math.sqrt(delta)) / (2*A);
+            double a = dx * dx + dy * dy;
+            double b = 2 * (fx * dx + fy * dy);
+            double c = fx * fx + fy * fy - radius * radius;
             
-            List<Double> ts = new ArrayList<>();
-            ts.add(0.0);
-            if (t1 > 0 && t1 < 1) ts.add(t1);
-            if (t2 > 0 && t2 < 1) ts.add(t2);
-            ts.add(1.0);
-            Collections.sort(ts);
-
-            for (int i = 0; i < ts.size()-1; i++) {
-                double midT = (ts.get(i) + ts.get(i+1)) / 2;
-                Point mid = interpolate(seg.start, seg.end, midT);
-                if (!isInside(mid)) {
-                    result.add(new PathSegment(interpolate(seg.start, seg.end, ts.get(i)),
-                                               interpolate(seg.start, seg.end, ts.get(i+1)), 
-                                               seg.isMowing));
-                }
-            }
-            return result;
-        }
-
-        boolean isInside(Point p) {
-            return (p.x-c.x)*(p.x-c.x) + (p.y-c.y)*(p.y-c.y) < r*r;
-        }
-    }
-
-    static class PolyObstacle extends Obstacle {
-        List<Point> points;
-        double minX, maxX, minY, maxY;
-
-        PolyObstacle(List<Point> pts) {
-            this.points = pts;
-            updateBounds();
-        }
-
-        void updateBounds() {
-            minX = minY = Double.MAX_VALUE;
-            maxX = maxY = -Double.MAX_VALUE;
-            for (Point p : points) {
-                minX = Math.min(minX, p.x); maxX = Math.max(maxX, p.x);
-                minY = Math.min(minY, p.y); maxY = Math.max(maxY, p.y);
-            }
-        }
-
-        boolean isInside(Point p) {
-            if (p.x < minX || p.x > maxX || p.y < minY || p.y > maxY) return false;
-            boolean result = false;
-            for (int i = 0, j = points.size() - 1; i < points.size(); j = i++) {
-                if ((points.get(i).y > p.y) != (points.get(j).y > p.y) &&
-                    (p.x < (points.get(j).x - points.get(i).x) * (p.y - points.get(i).y) / (points.get(j).y - points.get(i).y) + points.get(i).x)) {
-                    result = !result;
-                }
-            }
-            return result;
-        }
-
-        @Override
-        List<PathSegment> clip(PathSegment seg) {
-            List<Double> ts = new ArrayList<>();
-            ts.add(0.0);
-            ts.add(1.0);
-
-            // 璁$畻绾挎涓庨殰纰嶇墿姣忎竴鏉¤竟鐨勪氦鐐�
-            for (int i = 0; i < points.size(); i++) {
-                Point p1 = points.get(i);
-                Point p2 = points.get((i+1)%points.size());
-                double t = getIntersectionT(seg.start, seg.end, p1, p2);
-                if (t > 1e-6 && t < 1 - 1e-6) {
-                    ts.add(t);
-                }
-            }
-            Collections.sort(ts);
-
-            List<PathSegment> result = new ArrayList<>();
-            // 妫�鏌ユ瘡涓�灏忔鐨勪腑鐐规槸鍚﹀湪闅滅鐗╁唴
-            for (int i = 0; i < ts.size() - 1; i++) {
-                double tMid = (ts.get(i) + ts.get(i+1)) / 2.0;
-                // 濡傛灉涓ょ偣鏋佸叾鎺ヨ繎锛岃烦杩�
-                if (ts.get(i+1) - ts.get(i) < 1e-6) continue;
+            List<Double> tValues = new ArrayList<>();
+            tValues.add(0.0);
+            tValues.add(1.0);
+            
+            double discriminant = b * b - 4 * a * c;
+            if (discriminant > 0) {
+                double sqrtDisc = Math.sqrt(discriminant);
+                double t1 = (-b - sqrtDisc) / (2 * a);
+                double t2 = (-b + sqrtDisc) / (2 * a);
                 
-                Point mid = interpolate(seg.start, seg.end, tMid);
-                if (!isInside(mid)) {
-                    // 鍦ㄥ閮紝淇濈暀
-                    Point s = interpolate(seg.start, seg.end, ts.get(i));
-                    Point e = interpolate(seg.start, seg.end, ts.get(i+1));
-                    result.add(new PathSegment(s, e, seg.isMowing));
+                if (t1 > EPS && t1 < 1 - EPS) tValues.add(t1);
+                if (t2 > EPS && t2 < 1 - EPS) tValues.add(t2);
+            }
+            
+            Collections.sort(tValues);
+            List<PathSegment> result = new ArrayList<>();
+            
+            for (int i = 0; i < tValues.size() - 1; i++) {
+                double t1 = tValues.get(i);
+                double t2 = tValues.get(i + 1);
+                double tMid = (t1 + t2) / 2;
+                
+                Point midPoint = interpolate(seg.start, seg.end, tMid);
+                if (!containsPoint(midPoint)) {
+                    Point start = interpolate(seg.start, seg.end, t1);
+                    Point end = interpolate(seg.start, seg.end, t2);
+                    result.add(new PathSegment(start, end, seg.isMowing));
                 }
             }
+            
             return result;
         }
-    }
-
-    // --- 閫氱敤鍑犱綍绠楁硶 ---
-
-    private static List<Point> getOffsetPolygon(List<Point> points, double offset) {
-        List<Point> result = new ArrayList<>();
-        int n = points.size();
-        for (int i = 0; i < n; i++) {
-            Point p1 = points.get((i - 1 + n) % n);
-            Point p2 = points.get(i);
-            Point p3 = points.get((i + 1) % n);
-            
-            // 鍚戦噺 p1->p2 鍜� p2->p3
-            double v1x = p2.x - p1.x, v1y = p2.y - p1.y;
-            double v2x = p3.x - p2.x, v2y = p3.y - p2.y;
-            double l1 = Math.hypot(v1x, v1y), l2 = Math.hypot(v2x, v2y);
-            
-            if (l1 < 1e-5 || l2 < 1e-5) continue;
-
-            // 娉曞悜閲� (鍚戝乏杞�90搴�: -y, x)
-            double n1x = -v1y / l1, n1y = v1x / l1;
-            double n2x = -v2y / l2, n2y = v2x / l2;
-
-            // 瑙掑钩鍒嗙嚎
-            double bx = n1x + n2x, by = n1y + n2y;
-            double bl = Math.hypot(bx, by);
-            if (bl < 1e-5) { bx = n1x; by = n1y; } 
-            else { bx /= bl; by /= bl; }
-
-            // 淇闀垮害 offset / sin(theta/2) = offset / dot(n1, b)
-            double dot = n1x * bx + n1y * by;
-            double dist = offset / Math.max(Math.abs(dot), 0.1); // 闃叉灏栬杩囬暱
-            
-            // 闃堝�奸檺鍒讹紝闃叉鑷氦鎴栫暩鍙樿繃澶�
-            dist = Math.signum(offset) * Math.min(Math.abs(dist), Math.abs(offset) * 3);
-
-            result.add(new Point(p2.x + bx * dist, p2.y + by * dist));
-        }
-        return result;
-    }
-
-    private static double findOptimalAngle(List<Point> poly) {
-        double bestA = 0, minH = Double.MAX_VALUE;
-        for (int i = 0; i < poly.size(); i++) {
-            Point p1 = poly.get(i), p2 = poly.get((i + 1) % poly.size());
-            double a = Math.atan2(p2.y - p1.y, p2.x - p1.x);
-            double h = calcHeight(poly, a);
-            if (h < minH) { minH = h; bestA = a; }
-        }
-        return bestA;
-    }
-
-    private static double calcHeight(List<Point> poly, double ang) {
-        double min = Double.MAX_VALUE, max = -Double.MAX_VALUE;
-        for (Point p : poly) {
-            Point r = rotatePoint(p, -ang);
-            min = Math.min(min, r.y); max = Math.max(max, r.y);
-        }
-        return max - min;
-    }
-
-    private static double getIntersectionT(Point a, Point b, Point c, Point d) {
-        double ux = b.x - a.x, uy = b.y - a.y;
-        double vx = d.x - c.x, vy = d.y - c.y;
-        double det = vx * uy - vy * ux;
-        if (Math.abs(det) < 1e-8) return -1;
         
-        double wx = c.x - a.x, wy = c.y - a.y;
-        double t = (vx * wy - vy * wx) / det;
-        double u = (ux * wy - uy * wx) / det;
+        @Override
+        boolean doesSegmentIntersect(Point p1, Point p2) {
+            Point closest = closestPointOnSegment(center, p1, p2);
+            // 灏嗕笌鍦嗙殑鐩稿垏涔熻涓虹浉浜わ紝閬垮厤璺緞鎿﹁竟
+            return distance(center, closest) <= radius + EPS;
+        }
         
-        if (u >= 0 && u <= 1) return t; // 鍙繚璇佷氦鐐瑰湪绾挎CD涓婏紝t鏄疉B涓婄殑姣斾緥
-        return -1;
-    }
-
-    private static List<Double> getXIntersections(List<Point> poly, double y) {
-        List<Double> res = new ArrayList<>();
-        for (int i = 0; i < poly.size(); i++) {
-            Point p1 = poly.get(i), p2 = poly.get((i + 1) % poly.size());
-            if ((p1.y <= y && p2.y > y) || (p2.y <= y && p1.y > y)) {
-                res.add(p1.x + (y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y));
+        @Override
+        boolean containsPoint(Point p) {
+            return distance(center, p) < radius - EPS;
+        }
+        
+        @Override
+        List<Point> getKeyPoints() {
+            List<Point> points = new ArrayList<>();
+            int numPoints = 8; // 鍏竟褰㈣繎浼�
+            
+            for (int i = 0; i < numPoints; i++) {
+                double angle = 2 * Math.PI * i / numPoints;
+                points.add(new Point(
+                    center.x + radius * Math.cos(angle),
+                    center.y + radius * Math.sin(angle)
+                ));
             }
+            
+            return points;
         }
-        return res;
     }
-
-    private static List<Point> alignBoundaryStart(List<Point> poly, Point target) {
-        if (target == null) return poly;
-        int idx = 0; double minD = Double.MAX_VALUE;
-        for (int i = 0; i < poly.size(); i++) {
-            double d = distance(poly.get(i), target);
-            if (d < minD) { minD = d; idx = i; }
+    
+    /**
+     * 璺緞娈�
+     */
+    public static class PathSegment {
+        public Point start, end;
+        public boolean isMowing;
+        
+        public PathSegment(Point start, Point end, boolean isMowing) {
+            this.start = start;
+            this.end = end;
+            this.isMowing = isMowing;
         }
-        List<Point> res = new ArrayList<>();
-        for (int i = 0; i < poly.size(); i++) res.add(poly.get((idx + i) % poly.size()));
-        return res;
-    }
-
-    private static void ensureCounterClockwise(List<Point> pts) {
-        double s = 0;
-        for (int i = 0; i < pts.size(); i++) {
-            Point p1 = pts.get(i), p2 = pts.get((i + 1) % pts.size());
-            s += (p2.x - p1.x) * (p2.y + p1.y);
+        
+        @Override
+        public String toString() {
+            return String.format("%s -> %s [%s]", start, end, isMowing ? "MOW" : "MOVE");
         }
-        if (s > 0) Collections.reverse(pts); // 鍋囪灞忓箷鍧愭爣绯籝鍚戜笅锛熼�氬父澶氳竟褰㈤潰绉叕寮弒>0鏄『鏃堕拡(Y鍚戜笅)鎴栭�嗘椂閽�(Y鍚戜笂)
-        // 姝ゅ娌跨敤鎮ㄤ唬鐮佺殑閫昏緫锛氬鏋淪um>0 鍒欏弽杞��
     }
-
-    private static Point rotatePoint(Point p, double a) {
-        double c = Math.cos(a), s = Math.sin(a);
-        return new Point(p.x * c - p.y * s, p.x * s + p.y * c);
+    
+    /**
+     * 鐐圭被
+     */
+    public static class Point {
+        public double x, y;
+        
+        public Point(double x, double y) {
+            this.x = x;
+            this.y = y;
+        }
+        
+        @Override
+        public boolean equals(Object obj) {
+            if (this == obj) return true;
+            if (!(obj instanceof Point)) return false;
+            Point other = (Point) obj;
+            return Math.abs(x - other.x) < EPS && Math.abs(y - other.y) < EPS;
+        }
+        
+        @Override
+        public int hashCode() {
+            return Double.hashCode(x) * 31 + Double.hashCode(y);
+        }
+        
+        @Override
+        public String toString() {
+            return String.format("(%.2f, %.2f)", x, y);
+        }
+    }
+    
+    /**
+     * 杈圭晫妗�
+     */
+    private static class Bounds {
+        double minX, maxX, minY, maxY;
+        
+        Bounds(double minX, double maxX, double minY, double maxY) {
+            this.minX = minX;
+            this.maxX = maxX;
+            this.minY = minY;
+            this.maxY = maxY;
+        }
+    }
+    
+    // ==================== 鍑犱綍宸ュ叿鍑芥暟 ====================
+    
+    private static Double lineIntersection(Point a1, Point a2, Point b1, Point b2) {
+        double det = (a2.x - a1.x) * (b2.y - b1.y) - (a2.y - a1.y) * (b2.x - b1.x);
+        
+        if (Math.abs(det) < EPS) return null;
+        
+        double t = ((b1.x - a1.x) * (b2.y - b1.y) - (b1.y - a1.y) * (b2.x - b1.x)) / det;
+        double u = ((a1.x - b1.x) * (a2.y - a1.y) - (a1.y - b1.y) * (a2.x - a1.x)) / (-det);
+        
+        if (t >= -EPS && t <= 1 + EPS && u >= -EPS && u <= 1 + EPS) {
+            return Math.max(0, Math.min(1, t));
+        }
+        
+        return null;
+    }
+    
+    private static boolean lineSegmentIntersection(Point a1, Point a2, Point b1, Point b2) {
+        Double t = lineIntersection(a1, a2, b1, b2);
+        return t != null;
     }
     
     private static Point interpolate(Point a, Point b, double t) {
         return new Point(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);
     }
-
-    private static double distance(Point a, Point b) {
-        return Math.hypot(a.x - b.x, a.y - b.y);
-    }
-
-    private static List<Point> parseCoordinates(String s) {
-        List<Point> pts = new ArrayList<>();
-        if (s == null || s.isEmpty()) return pts;
-        for (String p : s.split(";")) {
-            String[] xy = p.split(",");
-            if (xy.length >= 2) pts.add(new Point(Double.parseDouble(xy[0]), Double.parseDouble(xy[1])));
-        }
-        if (pts.size() > 1 && distance(pts.get(0), pts.get(pts.size() - 1)) < 1e-4) pts.remove(pts.size() - 1);
-        return pts;
-    }
-
-    // --- 鏁版嵁缁撴瀯 ---
-    public static class Point {
-        public double x, y;
-        public Point(double x, double y) { this.x = x; this.y = y; }
-    }
-
-    public static class PathSegment {
-        public Point start, end;
-        public boolean isMowing;
-        public PathSegment(Point s, Point e, boolean m) { this.start = s; this.end = e; this.isMowing = m; }
-        @Override
-        public String toString() { return String.format("%.6f,%.6f;%.6f,%.6f", start.x, start.y, end.x, end.y); }
-    }
+    
+    private static Point closestPointOnSegment(Point p, Point a, Point b) {
+        double ax = b.x - a.x;
+        double ay = b.y - a.y;
+        double bx = p.x - a.x;
+        double by = p.y - a.y;
+        
+        double dot = ax * bx + ay * by;
+        double lenSq = ax * ax + ay * ay;
+        
+        double t = (lenSq > EPS) ? Math.max(0, Math.min(1, dot / lenSq)) : 0;
+        
+        return new Point(a.x + t * ax, a.y + t * ay);
+    }    
+   
 }
\ No newline at end of file

--
Gitblit v1.10.0