From 7881cef5c3dcea8e6037101db2c3eeb2fd3ba5da Mon Sep 17 00:00:00 2001
From: 826220679@qq.com <826220679@qq.com>
Date: 星期六, 27 十二月 2025 23:42:36 +0800
Subject: [PATCH] 1211

---
 src/lujing/YixinglujingNoObstacle.java |  861 +++++++++++++++++++++++++++++++++------------------------
 1 files changed, 500 insertions(+), 361 deletions(-)

diff --git a/src/lujing/YixinglujingNoObstacle.java b/src/lujing/YixinglujingNoObstacle.java
index ae28e81..31e87d5 100644
--- a/src/lujing/YixinglujingNoObstacle.java
+++ b/src/lujing/YixinglujingNoObstacle.java
@@ -1,454 +1,593 @@
 package lujing;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
+import java.util.*;
 
 /**
- * 寮傚舰锛堟棤闅滅鐗╋級鑽夊湴璺緞瑙勫垝绫� - 浼樺寲鐗� V2.0
- * * 鍔熻兘鐗圭偣锛�
- * 1. 鑷姩澶勭悊鍑瑰杈瑰舰锛堥�氳繃鑰冲垏娉曞垎鍓诧級
- * 2. 澧炲姞鈥滃洿杈光�濊矾寰勶紝淇濊瘉杈圭紭鍓茶崏鏁存磥
- * 3. 鑷姩璁$畻姣忎釜瀛愬尯鍩熺殑鏈�浼樻壂鎻忚搴︼紙鍑忓皯鎺夊ご娆℃暟锛�
- * 4. 鏅鸿兘鍖哄煙杩炴帴锛堟敮鎸佸弻鍚戣矾寰勯�夋嫨锛�
+ * 寮傚舰鑽夊湴璺緞瑙勫垝 - 鍑瑰杈瑰舰鍏煎浼樺寲鐗� V5.0
+ * 淇锛氳В鍐冲嚬澶氳竟褰㈡壂鎻忕嚎璺ㄨ秺杈圭晫鐨勯棶棰橈紝浼樺寲璺緞瀵归綈
  */
 public class YixinglujingNoObstacle {
-
-    // ==========================================
-    // 瀵瑰鎺ュ彛
-    // ==========================================
-
-    /**
-     * 瑙勫垝寮傚舰鑽夊湴鍓茶崏璺緞
-     *
-     * @param coordinates 鍦板潡杈圭晫鍧愭爣瀛楃涓诧紝鏍煎紡锛�"x1,y1;x2,y2;x3,y3;..."
-     * @param widthStr    鍓茶崏瀹藉害锛堢背锛夛紝濡� "0.34"
-     * @param marginStr   瀹夊叏杈硅窛锛堢背锛夛紝濡� "0.2"
-     * @return 璺緞娈靛垪琛�
-     */
+    // 寮�鍏筹細鏄惁寮哄埗鎵�鏈夐潪浣滀笟杩炴帴娌垮畨鍏ㄨ竟鐣岃璧帮紙閬垮厤浠讳綍鍐呭尯鐩寸嚎璺ㄨ秺锛�
+    // 鏀逛负鍙姩鎬佽缃紝鑷姩渚濇嵁鍦板潡褰㈢姸鍚敤
+    private static boolean FORCE_BOUNDARY_TRAVEL = true;
+    // 鐢ㄦ硶璇存槑锛堟棤闅滅鐗╄矾寰勮鍒掞級锛�
+    // - 鏂规硶鐢ㄩ�旓細鏍规嵁鍦板潡杈圭晫銆佸壊鑽夊搴︿笌瀹夊叏杈硅窛锛岀敓鎴愯鐩栧叏鍖哄煙鐨勫壊鑽夎矾寰勩��
+    // - 鍙傛暟锛�
+    //   coordinates锛氬湴鍧楄竟鐣屽潗鏍囧瓧绗︿覆锛屾牸寮� "x1,y1;x2,y2;..."锛岃嚦灏�3涓偣锛屽崟浣嶄负绫炽��
+    //   widthStr锛氬壊鑽夊搴︼紙瀛楃涓诧紝鍗曚綅绫筹級锛岀敤浜庣‘瀹氭壂鎻忕嚎闂磋窛銆�
+    //   marginStr锛氬畨鍏ㄨ竟璺濓紙瀛楃涓诧紝鍗曚綅绫筹級锛岀敤浜庡皢鍦板潡杈圭晫鍚戝唴鏀剁缉锛岄伩鍏嶈创杈逛綔涓氥��
+    // - 杩斿洖鍊硷細List<PathSegment>锛屽叾涓� PathSegment.start/end 涓哄潗鏍囩偣锛宨sMowing 涓� true 琛ㄧず鍓茶崏娈碉紝false 琛ㄧず绌鸿蛋娈点��
+    // - 澶辫触鎯呭喌锛氬綋杈圭晫鐐逛笉瓒虫垨鍐呯缉鍚庡尯鍩熻繃灏忥紝杩斿洖绌哄垪琛ㄣ��
+    // - 浣跨敤绀轰緥锛�
+    //   String boundary = "0,0;20,0;20,15;0,15";
+    //   String width = "0.3";
+    //   String margin = "0.5";
+    //   List<YixinglujingNoObstacle.PathSegment> path =
+    //       YixinglujingNoObstacle.planPath(boundary, width, margin);
     public static List<PathSegment> planPath(String coordinates, String widthStr, String marginStr) {
-        // 1. 鍙傛暟瑙f瀽涓庨澶勭悊
         List<Point> rawPoints = parseCoordinates(coordinates);
-        if (rawPoints.size() < 3) {
-            throw new IllegalArgumentException("澶氳竟褰㈢偣鏁颁笉瓒筹紝鏃犳硶鏋勬垚鍦板潡");
-        }
-        // 纭繚閫嗘椂閽堥『搴忥紝鏂逛究鍚庣画鍑犱綍璁$畻
-        ensureCounterClockwise(rawPoints);
+        if (rawPoints.size() < 3) return new ArrayList<>();
 
         double mowWidth = Double.parseDouble(widthStr);
         double safeMargin = Double.parseDouble(marginStr);
+
+        // 1. 棰勫鐞嗭細纭繚閫嗘椂閽堥『搴�
+        ensureCounterClockwise(rawPoints);
         
+        // 2. 鐢熸垚鍐呯缉澶氳竟褰紙瀹夊叏杈圭晫锛�
+        List<Point> boundary = getInsetPolygon(rawPoints, safeMargin);
+        if (boundary.size() < 3) return new ArrayList<>();
+
+        // 3. 纭畾鏈�浼樹綔涓氳搴�
+        double bestAngle = findOptimalAngle(boundary);
+
+        // 3.1 鑷姩鍒ゆ柇鏄惁闇�瑕佸己鍒舵部杈圭晫鏃呰锛堟娴嬪嚬閮�/澶氭鎵弿琛岋級
+        FORCE_BOUNDARY_TRAVEL = shouldForceBoundaryTravel(boundary, mowWidth, bestAngle);
+        
+        // 4. 鑾峰彇棣栦釜浣滀笟鐐癸紝鐢ㄤ簬瀵归綈鍥磋竟璧风偣
+        Point firstScanStart = getFirstScanPoint(boundary, mowWidth, bestAngle);
+
+        // 5. 瀵归綈鍥磋竟锛氫娇鍥磋竟鏈�鍚庣粨鏉熶簬闈犺繎鎵弿璧风偣鐨勪綅缃�
+        List<Point> alignedBoundary = alignBoundaryStart(boundary, firstScanStart);
+
         List<PathSegment> finalPath = new ArrayList<>();
 
-        // 2. 鐢熸垚鍥磋竟璺緞 (Contour Path)
-        // 杩欎竴姝ュ厛瑙勫垝涓�鍦堣疆寤擄紝瑙e喅寮傚舰杈圭紭闅惧鐞嗙殑闂
-        List<Point> contourPoly = getInsetPolygon(rawPoints, safeMargin);
-        
-        // 濡傛灉鍐呯缉鍚庨潰绉お灏忔垨鐐规暟涓嶈冻锛岀洿鎺ヨ繑鍥炵┖
-        if (contourPoly.size() < 3) {
-            return new ArrayList<>();
+        // 6. 绗竴闃舵锛氬洿杈硅矾寰�
+        for (int i = 0; i < alignedBoundary.size(); i++) {
+            Point pStart = alignedBoundary.get(i);
+            Point pEnd = alignedBoundary.get((i + 1) % alignedBoundary.size());
+            finalPath.add(new PathSegment(pStart, pEnd, true));
         }
 
-        // 灏嗗洿杈硅矾寰勫姞鍏ョ粨鏋�
-        for (int i = 0; i < contourPoly.size(); i++) {
-            Point p1 = contourPoly.get(i);
-            Point p2 = contourPoly.get((i + 1) % contourPoly.size());
-            finalPath.add(new PathSegment(p1, p2, true)); // true = 鍓茶崏
-        }
+        // 7. 绗簩闃舵锛氱敓鎴愬唴閮ㄦ壂鎻忚矾寰勶紙淇鍑归儴绌鸿秺闂锛�
+        Point lastEdgePos = alignedBoundary.get(0); 
+        List<PathSegment> scanPath = generateGlobalScanPath(boundary, mowWidth, bestAngle, lastEdgePos);
         
-        // 璁板綍鍥磋竟缁撴潫鍚庣殑浣嶇疆锛堥�氬父鍥炲埌鍥磋竟璧风偣锛�
-        Point endOfContour = contourPoly.get(0);
+        finalPath.addAll(scanPath);
 
-        // 3. 鍖哄煙鍒嗗壊 (Decomposition)
-        // 浣跨敤鑰冲垏娉曞皢鍥磋竟鍚庣殑澶氳竟褰㈠垎鍓蹭负澶氫釜鍑稿杈瑰舰锛堜笁瑙掑舰锛�
-        // 杩欐牱鍙互淇濊瘉瑕嗙洊鏃犻仐婕�
-        List<List<Point>> triangles = triangulatePolygon(contourPoly);
+        // 8. 鏈�缁堝畨鍏ㄥ噣鍖栵細纭繚鎵�鏈夋鍦ㄥ唴缂╄竟鐣屼笂鎴栧唴閮紙鑷姩璐磋竟闃堝�硷級
+        sanitizePath(finalPath, boundary, mowWidth, safeMargin);
 
-        // 4. 瀵规瘡涓尯鍩熺敓鎴愬唴閮ㄥ~鍏呰矾寰�
-        List<List<PathSegment>> allRegionPaths = new ArrayList<>();
-        
-        for (List<Point> triangle : triangles) {
-            // 銆愪紭鍖栥�戝鎵炬渶浼樻壂鎻忚搴︼細
-            // 閬嶅巻涓夎褰㈢殑涓夋潯杈癸紝璁$畻浠ュ摢鏉¤竟涓哄熀鍑嗘壂鎻忔椂锛岀敓鎴愮殑琛屾暟鏈�灏戯紙杞集鏈�灏戯級
-            List<PathSegment> regionPath = planConvexPathOptimal(triangle, mowWidth);
-            if (!regionPath.isEmpty()) {
-                allRegionPaths.add(regionPath);
-            }
+        // 9. 鏍煎紡鍖栧潗鏍囷細淇濈暀涓や綅灏忔暟
+        for (PathSegment segment : finalPath) {
+            segment.start.x = Math.round(segment.start.x * 100.0) / 100.0;
+            segment.start.y = Math.round(segment.start.y * 100.0) / 100.0;
+            segment.end.x = Math.round(segment.end.x * 100.0) / 100.0;
+            segment.end.y = Math.round(segment.end.y * 100.0) / 100.0;
         }
 
-        // 5. 杩炴帴鎵�鏈夊唴閮ㄥ尯鍩� (Greedy Connection)
-        // 浠庡洿杈圭粨鏉熺偣寮�濮嬶紝瀵绘壘鏈�杩戠殑涓嬩竴涓尯鍩�
-        List<PathSegment> internalPaths = connectRegions(allRegionPaths, endOfContour);
-        finalPath.addAll(internalPaths);
-
         return finalPath;
     }
 
-    // ==========================================
-    // 鏍稿績瑙勫垝绠楁硶
-    // ==========================================
-
-    /**
-     * 瑙勫垝鍑稿杈瑰舰璺緞锛岃嚜鍔ㄩ�夋嫨鏈�浼樿搴�
-     */
-    private static List<PathSegment> planConvexPathOptimal(List<Point> polygon, double width) {
-        if (polygon.size() < 3) return new ArrayList<>();
-
-        double bestAngle = 0;
-        double minLines = Double.MAX_VALUE;
-
-        // 閬嶅巻澶氳竟褰㈢殑姣忎竴鏉¤竟锛屽皾璇曚互璇ヨ竟瑙掑害杩涜鎵弿
-        for (int i = 0; i < polygon.size(); i++) {
-            Point p1 = polygon.get(i);
-            Point p2 = polygon.get((i + 1) % polygon.size());
-            
-            // 璁$畻杈圭殑瑙掑害
-            double angle = Math.atan2(p2.y - p1.y, p2.x - p1.x);
-            
-            // 璁$畻鍦ㄨ繖涓搴︿笅锛屽杈瑰舰鐨勫瀭鐩存姇褰遍珮搴�
-            // 楂樺害瓒婂皬锛屾剰鍛崇潃娌挎鏂瑰悜鎵弿鐨勮鏁拌秺灏戯紝鏁堢巼瓒婇珮
-            double height = calculatePolygonHeight(polygon, -angle);
-            
-            if (height < minLines) {
-                minLines = height;
-                bestAngle = angle;
+    // 瀵规墍鏈夎矾寰勬杩涜瀹夊叏鍑�鍖栵細
+    // - 闈炰綔涓氭锛氱粺涓�娌胯竟鐣岃矾寰勬浛鎹�
+    // - 浣滀笟娈碉細鑻ョ鐐瑰湪澶栨垨娈典笌杈圭晫鐩镐氦锛屽惛闄勭鐐瑰埌杈圭晫骞跺悜鍐呬晶鍋忕Щ epsilon
+    private static void sanitizePath(List<PathSegment> segments, List<Point> polygon, double width, double margin) {
+        double epsilon = computeAutoInnerOffset(polygon, width, margin);
+        List<PathSegment> sanitized = new ArrayList<>();
+        for (PathSegment s : segments) {
+            boolean startInside = isPointInPolygon(s.start, polygon);
+            boolean endInside = isPointInPolygon(s.end, polygon);
+            boolean intersects = segmentIntersectsBoundary(s.start, s.end, polygon);
+            if (!s.isMowing) {
+                // 闈炰綔涓氭缁熶竴鏇挎崲涓烘部杈圭晫璺緞
+                List<Point> path = getBoundaryPathWithSnap(s.start, s.end, polygon);
+                for (int i = 0; i < path.size() - 1; i++) {
+                    sanitized.add(new PathSegment(path.get(i), path.get(i+1), false));
+                }
+            } else {
+                if (!startInside || !endInside || intersects) {
+                    SnapResult s1 = snapToBoundary(s.start, polygon);
+                    SnapResult s2 = snapToBoundary(s.end, polygon);
+                    Point p1 = pushInsideOnEdge(s1, polygon, epsilon);
+                    Point p2 = pushInsideOnEdge(s2, polygon, epsilon);
+                    sanitized.add(new PathSegment(p1, p2, true));
+                } else {
+                    sanitized.add(s);
+                }
             }
         }
-
-        // 浣跨敤鏈�浣宠搴︾敓鎴愯矾寰�
-        return generatePathWithAngle(polygon, width, bestAngle);
+        segments.clear();
+        segments.addAll(sanitized);
     }
 
-    /**
-     * 鏍规嵁鎸囧畾瑙掑害鐢熸垚寮撳瓧褰㈣矾寰�
-     */
-    private static List<PathSegment> generatePathWithAngle(List<Point> polygon, double width, double angle) {
-        // 1. 灏嗗杈瑰舰鏃嬭浆鍒版按骞充綅缃�
-        List<Point> rotatedPoints = new ArrayList<>();
-        for (Point p : polygon) {
-            rotatedPoints.add(rotatePoint(p, -angle));
+    private static boolean segmentIntersectsBoundary(Point a, Point b, List<Point> polygon) {
+        for (int i = 0; i < polygon.size(); i++) {
+            Point c = polygon.get(i);
+            Point d = polygon.get((i + 1) % polygon.size());
+            // 蹇界暐鍏变韩绔偣鐨勭浉浜�
+            if (isSamePoint(a, c) || isSamePoint(a, d) || isSamePoint(b, c) || isSamePoint(b, d)) continue;
+            if (segmentsIntersect(a, b, c, d)) return true;
         }
+        return false;
+    }
 
-        // 2. 璁$畻Y杞磋寖鍥�
-        double minY = Double.MAX_VALUE;
-        double maxY = -Double.MAX_VALUE;
-        for (Point p : rotatedPoints) {
+    // 灏嗚竟鐣屼笂鐨勬姇褰辩偣鍚戝唴渚у亸绉� epsilon
+    private static Point pushInsideOnEdge(SnapResult sr, List<Point> poly, double epsilon) {
+        int i = sr.edgeIndex;
+        Point s = poly.get(i);
+        Point e = poly.get((i + 1) % poly.size());
+        double dx = e.x - s.x, dy = e.y - s.y;
+        double len = Math.hypot(dx, dy);
+        if (len < 1e-6) return sr.onEdge;
+        // 瀵逛簬閫嗘椂閽堬紙CCW锛夊杈瑰舰锛屽乏杞硶鍚戦噺 (-dy, dx) 鎸囧悜鍐呬晶
+        double nx = -dy / len, ny = dx / len;
+        return new Point(sr.onEdge.x + nx * epsilon, sr.onEdge.y + ny * epsilon);
+    }
+
+    // 鑷姩璁$畻璐磋竟鍐呭亸绉婚槇鍊� epsilon锛氭牴鎹湴鍧楀昂搴︺�佹渶鐭竟銆佸壊鑽夊搴︿笌瀹夊叏杈硅窛缁煎悎浼扮畻
+    private static double computeAutoInnerOffset(List<Point> polygon, double width, double margin) {
+        double minEdge = Double.MAX_VALUE;
+        double minX = Double.MAX_VALUE, minY = Double.MAX_VALUE;
+        double maxX = -Double.MAX_VALUE, maxY = -Double.MAX_VALUE;
+        for (int i = 0; i < polygon.size(); i++) {
+            Point a = polygon.get(i);
+            Point b = polygon.get((i + 1) % polygon.size());
+            minEdge = Math.min(minEdge, Math.hypot(a.x - b.x, a.y - b.y));
+            minX = Math.min(minX, a.x); minY = Math.min(minY, a.y);
+            maxX = Math.max(maxX, a.x); maxY = Math.max(maxY, a.y);
+        }
+        double diag = Math.hypot(maxX - minX, maxY - minY);
+        // 鍩虹閲忥細鏁板�肩ǔ瀹氶渶瑕佺殑鏈�灏忓唴鍋忕Щ锛堝彇鍓插箙鐨�1%涓庡瑙掔嚎鐨�0.2%涔嬮棿鐨勮緝澶у�硷級
+        double base = Math.max(width * 0.01, diag * 0.002);
+        // 涓婇檺锛氫笉瓒呰繃瀹夊叏杈硅窛鐨�20%涓庡壊骞呯殑10%
+        double upper = Math.min(margin * 0.2, width * 0.1);
+        // 鍙楄竟闀跨害鏉燂細涓嶈秴杩囨渶鐭竟鐨�2%
+        double edgeLimit = minEdge * 0.02;
+        double eps = Math.min(upper, Math.max(base, edgeLimit * 0.5));
+        // 涓嬮檺/涓婇檺鏈�缁堥挸浣嶏細3mm 鍒� 5cm
+        eps = Math.max(0.003, Math.min(eps, 0.05));
+        return eps;
+    }
+
+    // 鏍规嵁鎵弿琛岀殑浜ょ偣鏁伴噺鏉ュ垽鏂槸鍚﹀瓨鍦ㄢ�滃娈佃鈥濓紙>=2娈碉級锛屾湁鍑归儴鎴栫獎閫氶亾鏃跺惎鐢ㄥ己鍒舵部杈圭晫鏃呰
+    private static boolean shouldForceBoundaryTravel(List<Point> polygon, double width, double angle) {
+        List<Point> rotatedPoly = new ArrayList<>();
+        for (Point p : polygon) rotatedPoly.add(rotatePoint(p, -angle));
+        double minY = Double.MAX_VALUE, maxY = -Double.MAX_VALUE;
+        for (Point p : rotatedPoly) { minY = Math.min(minY, p.y); maxY = Math.max(maxY, p.y); }
+
+        int multiSegmentRows = 0;
+        int totalRows = 0;
+        for (double y = minY + width/2; y <= maxY - width/2; y += width) {
+            List<Double> xIntersections = getXIntersections(rotatedPoly, y);
+            if (xIntersections.size() < 2) continue;
+            totalRows++;
+            if (xIntersections.size() >= 4) multiSegmentRows++; // 鍚屼竴琛屽嚭鐜颁袱涓強浠ヤ笂浣滀笟娈�
+        }
+        // 鍙鍑虹幇杩団�滃娈佃鈥濓紝灏卞己鍒舵部杈圭晫鏃呰锛涗篃鍙寜姣斾緥闃堝�艰Е鍙戯紙渚嬪 >=10%锛�
+        if (multiSegmentRows > 0) return true;
+        double ratio = totalRows == 0 ? 0.0 : (double) multiSegmentRows / (double) totalRows;
+        return ratio >= 0.1; // 鍏滃簳闃堝��
+    }
+
+    private static List<PathSegment> generateGlobalScanPath(List<Point> polygon, double width, double angle, Point currentPos) {
+        // 鍏堝皾璇曞皢鍑归櫡澶勮涓轰袱涓嫭绔嬪尯鍩燂紝鍒嗕袱娆℃壂鎻忥紝閬垮厤璺ㄥ尯鐩寸嚎杩炴帴
+        List<PathSegment> all = new ArrayList<>();
+        // 绗竴娆℃壂鎻忥細浼樺厛澶勭悊宸︿晶鍖哄煙锛坓roupIndex=0锛�
+        List<PathSegment> leftScan = generateScanPathForSide(polygon, width, angle, currentPos, 0);
+        all.addAll(leftScan);
+        Point posAfterLeft = leftScan.isEmpty() ? currentPos : leftScan.get(leftScan.size() - 1).end;
+        // 绗簩娆℃壂鎻忥細澶勭悊鍙充晶鍖哄煙锛坓roupIndex=1锛夛紝浠庡乏渚х粨鏉熺偣娌胯竟鐣屽埌鍙充晶棣栨
+        List<PathSegment> rightScan = generateScanPathForSide(polygon, width, angle, posAfterLeft, 1);
+        all.addAll(rightScan);
+        return all;
+    }
+
+    // 浠呮壂鎻忔寚瀹氫晶锛堝悓涓�鏉℃壂鎻忕嚎鐨勭 groupIndex 娈碉級锛岀敤浜庡皢鈥滆�虫湹鈥濊涓虹嫭绔嬪尯鍩�
+    private static List<PathSegment> generateScanPathForSide(List<Point> polygon, double width, double angle, Point currentPos, int sideIndex) {
+        List<PathSegment> segments = new ArrayList<>();
+        List<Point> rotatedPoly = new ArrayList<>();
+        for (Point p : polygon) rotatedPoly.add(rotatePoint(p, -angle));
+
+        double minY = Double.MAX_VALUE, maxY = -Double.MAX_VALUE;
+        for (Point p : rotatedPoly) {
             minY = Math.min(minY, p.y);
             maxY = Math.max(maxY, p.y);
         }
 
-        List<PathSegment> segments = new ArrayList<>();
         boolean leftToRight = true;
+        boolean firstSegmentConnected = false;
 
-        // 3. 鎵弿绾跨敓鎴� (浠� minY + width/2 寮�濮嬶紝淇濊瘉绗竴鍒�鍒囧湪澶氳竟褰㈠唴)
-        for (double y = minY + width / 2; y <= maxY; y += width) {
-            List<Double> intersections = new ArrayList<>();
-            for (int i = 0; i < rotatedPoints.size(); i++) {
-                Point p1 = rotatedPoints.get(i);
-                Point p2 = rotatedPoints.get((i + 1) % rotatedPoints.size());
-                
-                // 鍒ゆ柇鎵弿绾挎槸鍚︾┛杩囪竟
-                if ((p1.y <= y && p2.y > y) || (p2.y <= y && p1.y > y)) {
-                    double x = p1.x + (y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y);
-                    intersections.add(x);
+        for (double y = minY + width/2; y <= maxY - width/2; y += width) {
+            List<Double> xIntersections = getXIntersections(rotatedPoly, y);
+            if (xIntersections.size() < 2) continue;
+            Collections.sort(xIntersections);
+
+            // 鏋勫缓鏈鐨勪綔涓氭锛堝乏鍒板彸锛夊拰缁勭储寮�
+            List<PathSegment> lineSegmentsInRow = new ArrayList<>();
+            List<Integer> groupIndices = new ArrayList<>();
+            for (int i = 0, g = 0; i < xIntersections.size() - 1; i += 2, g++) {
+                Point pS = rotatePoint(new Point(xIntersections.get(i), y), angle);
+                Point pE = rotatePoint(new Point(xIntersections.get(i + 1), y), angle);
+                lineSegmentsInRow.add(new PathSegment(pS, pE, true));
+                groupIndices.add(g);
+            }
+
+            if (!leftToRight) {
+                Collections.reverse(lineSegmentsInRow);
+                Collections.reverse(groupIndices);
+                for (PathSegment s : lineSegmentsInRow) {
+                    Point temp = s.start; s.start = s.end; s.end = temp;
                 }
             }
-            Collections.sort(intersections);
 
-            // 鎴愬鐢熸垚绾挎
-            for (int k = 0; k < intersections.size() - 1; k += 2) {
-                double x1 = leftToRight ? intersections.get(k) : intersections.get(k + 1);
-                double x2 = leftToRight ? intersections.get(k + 1) : intersections.get(k);
-                
-                Point start = new Point(x1, y);
-                Point end = new Point(x2, y);
-
-                // 鏃嬭浆鍥炲師濮嬪潗鏍囩郴
-                Point originalStart = rotatePoint(start, angle);
-                Point originalEnd = rotatePoint(end, angle);
-
-                // 杩炴帴閫昏緫锛氬鏋滀笉鏄涓�娈碉紝闇�瑕佷粠涓婁竴娈电粓鐐硅繛杩囨潵
-                if (!segments.isEmpty()) {
-                    PathSegment prev = segments.get(segments.size() - 1);
-                    // 娣诲姞杩炴帴绾匡紙閫氬父绠椾綔鍓茶崏璺緞鐨勪竴閮ㄥ垎锛屼繚鎸佸紦瀛楀舰杩炵画锛�
-                    segments.add(new PathSegment(prev.end, originalStart, true));
-                }
-
-                segments.add(new PathSegment(originalStart, originalEnd, true));
+            int idxInRow = groupIndices.indexOf(sideIndex);
+            if (idxInRow == -1) {
+                // 鏈涓嶅寘鍚渚х殑浣滀笟娈碉紝璺宠繃
+                leftToRight = !leftToRight;
+                continue;
             }
-            leftToRight = !leftToRight; // 鎹㈠悜
+
+            PathSegment s = lineSegmentsInRow.get(idxInRow);
+            // 棣栨杩炴帴鎴栬法鍖鸿繛鎺ュ潎寮哄埗娌胯竟鐣岋紝閬垮厤绌胯秺鍑归櫡鍖�
+            if (Math.hypot(currentPos.x - s.start.x, currentPos.y - s.start.y) > 0.01) {
+                addBoundaryConnection(segments, currentPos, s.start, polygon);
+                firstSegmentConnected = true;
+            }
+            segments.add(s);
+            currentPos = s.end;
+            leftToRight = !leftToRight;
         }
-
         return segments;
     }
 
-    /**
-     * 杩炴帴鎵�鏈夊垎鍓插悗鐨勫尯鍩� (璐績绛栫暐 + 鍙屽悜浼樺寲)
-     */
-    private static List<PathSegment> connectRegions(List<List<PathSegment>> regions, Point startPoint) {
-        List<PathSegment> result = new ArrayList<>();
-        if (regions.isEmpty()) return result;
-
-        List<List<PathSegment>> remaining = new ArrayList<>(regions);
-        Point currentPos = startPoint;
-
-        while (!remaining.isEmpty()) {
-            int bestIndex = -1;
-            double minDist = Double.MAX_VALUE;
-            boolean needReverse = false;
-
-            // 瀵绘壘绂诲綋鍓嶄綅缃渶杩戠殑鍖哄煙璧风偣鎴栫粓鐐�
-            for (int i = 0; i < remaining.size(); i++) {
-                List<PathSegment> region = remaining.get(i);
-                Point pStart = region.get(0).start;
-                Point pEnd = region.get(region.size() - 1).end;
-
-                double dStart = distance(currentPos, pStart);
-                double dEnd = distance(currentPos, pEnd);
-
-                // 妫�鏌ユ鍚戣繘鍏�
-                if (dStart < minDist) {
-                    minDist = dStart;
-                    bestIndex = i;
-                    needReverse = false;
-                }
-                // 妫�鏌ュ弽鍚戣繘鍏ワ紙鍊掔潃鍓茶崏濡傛灉鏇磋繎锛�
-                if (dEnd < minDist) {
-                    minDist = dEnd;
-                    bestIndex = i;
-                    needReverse = true;
-                }
-            }
-
-            if (bestIndex != -1) {
-                List<PathSegment> targetRegion = remaining.remove(bestIndex);
-                
-                if (needReverse) {
-                    // 鍙嶈浆璇ュ尯鍩熺殑鎵�鏈夎矾寰�
-                    List<PathSegment> reversedRegion = new ArrayList<>();
-                    for (int k = targetRegion.size() - 1; k >= 0; k--) {
-                        PathSegment seg = targetRegion.get(k);
-                        // 浜ゆ崲璧风偣缁堢偣
-                        reversedRegion.add(new PathSegment(seg.end, seg.start, seg.isMowing));
-                    }
-                    targetRegion = reversedRegion;
-                }
-
-                // 娣诲姞杩囨浮璺緞锛堟姮鍒�绉诲姩锛宨sMowing=false锛�
-                Point nextStart = targetRegion.get(0).start;
-                // 鍙湁璺濈鏄捐憲鎵嶆坊鍔犵Щ鍔ㄦ
-                if (distance(currentPos, nextStart) > 0.01) {
-                    result.add(new PathSegment(currentPos, nextStart, false));
-                }
-
-                result.addAll(targetRegion);
-                currentPos = targetRegion.get(targetRegion.size() - 1).end;
-            } else {
-                break; // 闃插尽鎬т唬鐮�
-            }
-        }
-        return result;
+    private static Point getFirstScanPoint(List<Point> polygon, double width, double angle) {
+        List<Point> rotatedPoly = new ArrayList<>();
+        for (Point p : polygon) rotatedPoly.add(rotatePoint(p, -angle));
+        double minY = Double.MAX_VALUE;
+        for (Point p : rotatedPoly) minY = Math.min(minY, p.y);
+        
+        double firstY = minY + width/2;
+        List<Double> xInter = getXIntersections(rotatedPoly, firstY);
+        if (xInter.isEmpty()) return polygon.get(0);
+        Collections.sort(xInter);
+        return rotatePoint(new Point(xInter.get(0), firstY), angle);
     }
 
-    // ==========================================
-    // 鍑犱綍杩愮畻杈呭姪鏂规硶
-    // ==========================================
+    private static List<Point> alignBoundaryStart(List<Point> boundary, Point targetStart) {
+        int bestIdx = 0;
+        double minDist = Double.MAX_VALUE;
+        for (int i = 0; i < boundary.size(); i++) {
+            double d = Math.hypot(boundary.get(i).x - targetStart.x, boundary.get(i).y - targetStart.y);
+            if (d < minDist) { minDist = d; bestIdx = i; }
+        }
+        List<Point> aligned = new ArrayList<>();
+        for (int i = 0; i < boundary.size(); i++) {
+            aligned.add(boundary.get((bestIdx + i) % boundary.size()));
+        }
+        return aligned;
+    }
 
-    /**
-     * 鍐呯缉澶氳竟褰� (鍩轰簬瑙掑钩鍒嗙嚎)
-     */
-    private static List<Point> getInsetPolygon(List<Point> points, double margin) {
+    private static List<Double> getXIntersections(List<Point> rotatedPoly, double y) {
+        List<Double> xIntersections = new ArrayList<>();
+        double tolerance = 1e-6;
+        
+        for (int i = 0; i < rotatedPoly.size(); i++) {
+            Point p1 = rotatedPoly.get(i);
+            Point p2 = rotatedPoly.get((i + 1) % rotatedPoly.size());
+            
+            // 璺宠繃姘村钩杈癸紙閬垮厤涓庢壂鎻忕嚎閲嶅悎鏃剁殑鐗规畩鎯呭喌锛�
+            if (Math.abs(p1.y - p2.y) < tolerance) {
+                continue;
+            }
+            
+            // 妫�鏌ユ槸鍚︾浉浜わ紙浣跨敤涓ユ牸涓嶇瓑寮忛伩鍏嶉《鐐归噸澶嶏級
+            if ((p1.y < y && p2.y >= y) || (p2.y < y && p1.y >= y)) {
+                double x = p1.x + (y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y);
+                // 绠�鍗曞幓閲嶏細妫�鏌ユ槸鍚﹀凡瀛樺湪鐩歌繎鐨勭偣
+                boolean isDuplicate = false;
+                for (double existingX : xIntersections) {
+                    if (Math.abs(x - existingX) < tolerance) {
+                        isDuplicate = true;
+                        break;
+                    }
+                }
+                if (!isDuplicate) {
+                    xIntersections.add(x);
+                }
+            }
+        }
+        return xIntersections;
+    }
+
+    private static double findOptimalAngle(List<Point> polygon) {
+        double bestAngle = 0;
+        double minHeight = Double.MAX_VALUE;
+        for (int i = 0; i < polygon.size(); i++) {
+            Point p1 = polygon.get(i), p2 = polygon.get((i + 1) % polygon.size());
+            double angle = Math.atan2(p2.y - p1.y, p2.x - p1.x);
+            double h = calculateHeightAtAngle(polygon, angle);
+            if (h < minHeight) { minHeight = h; bestAngle = angle; }
+        }
+        return bestAngle;
+    }
+
+    private static double calculateHeightAtAngle(List<Point> poly, double angle) {
+        double minY = Double.MAX_VALUE, maxY = -Double.MAX_VALUE;
+        for (Point p : poly) {
+            Point rp = rotatePoint(p, -angle);
+            minY = Math.min(minY, rp.y); maxY = Math.max(maxY, rp.y);
+        }
+        return maxY - minY;
+    }
+
+    public static List<Point> getInsetPolygon(List<Point> points, double margin) {
         List<Point> result = new ArrayList<>();
         int n = points.size();
-
         for (int i = 0; i < n; i++) {
             Point pPrev = points.get((i - 1 + n) % n);
             Point pCurr = points.get(i);
             Point pNext = points.get((i + 1) % n);
 
-            Point v1 = new Point(pCurr.x - pPrev.x, pCurr.y - pPrev.y);
-            Point v2 = new Point(pNext.x - pCurr.x, pNext.y - pCurr.y);
+            double d1x = pCurr.x - pPrev.x, d1y = pCurr.y - pPrev.y;
+            double l1 = Math.hypot(d1x, d1y);
+            double d2x = pNext.x - pCurr.x, d2y = pNext.y - pCurr.y;
+            double l2 = Math.hypot(d2x, d2y);
 
-            double len1 = Math.hypot(v1.x, v1.y);
-            double len2 = Math.hypot(v2.x, v2.y);
+            if (l1 < 1e-6 || l2 < 1e-6) continue;
 
-            if (len1 < 1e-6 || len2 < 1e-6) continue;
+            // 鍗曚綅娉曞悜閲�
+            double n1x = -d1y / l1, n1y = d1x / l1;
+            double n2x = -d2y / l2, n2y = d2x / l2;
 
-            // 褰掍竴鍖栧悜閲�
-            Point n1 = new Point(v1.x / len1, v1.y / len1);
-            Point n2 = new Point(v2.x / len2, v2.y / len2);
+            // 瑙掑钩鍒嗙嚎鏂瑰悜
+            double bisectorX = n1x + n2x, bisectorY = n1y + n2y;
+            double bLen = Math.hypot(bisectorX, bisectorY);
+            if (bLen < 1e-6) { bisectorX = n1x; bisectorY = n1y; } 
+            else { bisectorX /= bLen; bisectorY /= bLen; }
 
-            // 璁$畻骞冲垎绾挎柟鍚�
-            // v1鍙嶅悜 + v2
-            Point bisector = new Point(-n1.x + n2.x, -n1.y + n2.y);
-            double biLen = Math.hypot(bisector.x, bisector.y);
+            double cosHalfAngle = n1x * bisectorX + n1y * bisectorY;
+            double dist = margin / Math.max(cosHalfAngle, 0.1); 
             
-            // 璁$畻鍗婅 sin(theta/2)
-            double cross = n1.x * n2.y - n1.y * n2.x; // 鍙夌Н鍒ゆ柇杞悜
-            
-            // 榛樿鍚戝乏渚у唴缂� (CCW澶氳竟褰�)
-            if (biLen < 1e-6) {
-                // 鍏辩嚎锛屾部娉曠嚎鏂瑰悜
-                bisector = new Point(-n1.y, n1.x);
-            } else {
-                bisector.x /= biLen;
-                bisector.y /= biLen;
-            }
+            // 闄愬埗鏈�澶т綅绉婚噺锛岄槻姝㈡瀬灏栬鐣稿彉
+            dist = Math.min(dist, margin * 5); 
 
-            // 璁$畻鍋忕Щ璺濈
-            double dot = n1.x * n2.x + n1.y * n2.y;
-            double angle = Math.acos(Math.max(-1, Math.min(1, dot)));
-            double dist = margin / Math.sin(angle / 2.0);
-
-            // 鏂瑰悜淇锛氱‘淇濆钩鍒嗙嚎鎸囧悜澶氳竟褰㈠唴閮紙閫嗘椂閽堝杈瑰舰鐨勫乏渚э級
-            Point leftNormal = new Point(-n1.y, n1.x);
-            if (bisector.x * leftNormal.x + bisector.y * leftNormal.y < 0) {
-                 bisector.x = -bisector.x;
-                 bisector.y = -bisector.y;
-            }
-            
-            // 濡傛灉鏄嚬瑙掞紙cross < 0锛夛紝骞冲垎绾挎寚鍚戝閮紝璺濈闇�瑕佸弽杞垨鑰呯壒娈婂鐞�
-            // 绠�鍗曞鐞嗭細瀵逛簬鍑硅锛屽亸绉荤偣瀹為檯涓婁細杩滅鍘熺偣锛屼笂杩伴�昏緫閫氬父鑳借鐩栵紝
-            // 浣嗘瀬绔攼瑙掑彲鑳藉鑷磀ist杩囧ぇ銆傛澶勫仛绠�鍗曟埅鏂繚鎶ゆ槸涓嶅鐨勶紝
-            // 浣嗛拡瀵逛竴鑸崏鍦板舰鐘讹紝姝ら�昏緫鍙敤銆�
-            
-            result.add(new Point(pCurr.x + bisector.x * dist, pCurr.y + bisector.y * dist));
+            result.add(new Point(pCurr.x + bisectorX * dist, pCurr.y + bisectorY * dist));
         }
         return result;
     }
 
-    /**
-     * 鑰冲垏娉曞垎鍓插杈瑰舰
-     */
-    private static List<List<Point>> triangulatePolygon(List<Point> poly) {
-        List<List<Point>> triangles = new ArrayList<>();
-        List<Point> remaining = new ArrayList<>(poly);
-
-        int maxIter = remaining.size() * 3;
-        int iter = 0;
-
-        while (remaining.size() > 3 && iter++ < maxIter) {
-            int n = remaining.size();
-            boolean earFound = false;
-
-            for (int i = 0; i < n; i++) {
-                Point prev = remaining.get((i - 1 + n) % n);
-                Point curr = remaining.get(i);
-                Point next = remaining.get((i + 1) % n);
-
-                if (isConvex(prev, curr, next)) {
-                    boolean hasPoint = false;
-                    for (int j = 0; j < n; j++) {
-                        if (j == i || j == (i - 1 + n) % n || j == (i + 1) % n) continue;
-                        if (isPointInTriangle(remaining.get(j), prev, curr, next)) {
-                            hasPoint = true;
-                            break;
-                        }
-                    }
-
-                    if (!hasPoint) {
-                        List<Point> tri = new ArrayList<>();
-                        tri.add(prev); tri.add(curr); tri.add(next);
-                        triangles.add(tri);
-                        remaining.remove(i);
-                        earFound = true;
-                        break;
-                    }
-                }
-            }
-            if (!earFound) break;
+    private static void addSafeConnection(List<PathSegment> segments, Point start, Point end, List<Point> polygon) {
+        if (!FORCE_BOUNDARY_TRAVEL && isSegmentSafe(start, end, polygon)) {
+            segments.add(new PathSegment(start, end, false));
+            return;
         }
-
-        if (remaining.size() == 3) {
-            triangles.add(remaining);
+        List<Point> path = getBoundaryPathWithSnap(start, end, polygon);
+        for (int i = 0; i < path.size() - 1; i++) {
+            segments.add(new PathSegment(path.get(i), path.get(i+1), false));
         }
-        return triangles;
     }
 
-    private static double calculatePolygonHeight(List<Point> poly, double angle) {
-        double minY = Double.MAX_VALUE;
-        double maxY = -Double.MAX_VALUE;
-        for (Point p : poly) {
-            Point r = rotatePoint(p, angle);
-            minY = Math.min(minY, r.y);
-            maxY = Math.max(maxY, r.y);
+    // 寮哄埗娌胯竟鐣岀粫琛岀殑杩炴帴锛堜笉鍋氱洿绾垮畨鍏ㄥ垽鏂級锛岀敤鏉ュ湪鍚屼竴鎵弿琛岀殑澶氫釜浣滀笟娈典箣闂磋烦杞�
+    private static void addBoundaryConnection(List<PathSegment> segments, Point start, Point end, List<Point> polygon) {
+        List<Point> path = getBoundaryPathWithSnap(start, end, polygon);
+        for (int i = 0; i < path.size() - 1; i++) {
+            segments.add(new PathSegment(path.get(i), path.get(i+1), false));
         }
-        return maxY - minY;
+    }
+
+    // 灏嗕换鎰忎袱鐐归�氳繃鈥滃惛闄勫埌杈圭晫鈥濆悗娌胯竟鐣屾渶鐭矾寰勮繛鎺�
+    private static List<Point> getBoundaryPathWithSnap(Point start, Point end, List<Point> polygon) {
+        SnapResult s1 = snapToBoundary(start, polygon);
+        SnapResult s2 = snapToBoundary(end, polygon);
+        int n = polygon.size();
+
+        // 鍓嶅悜璺緞锛堥『杈癸級
+        List<Point> pathFwd = new ArrayList<>();
+        pathFwd.add(start);
+        pathFwd.add(s1.onEdge);
+        int curr = s1.edgeIndex;
+        while (curr != s2.edgeIndex) {
+            pathFwd.add(polygon.get((curr + 1) % n));
+            curr = (curr + 1) % n;
+        }
+        pathFwd.add(s2.onEdge);
+        pathFwd.add(end);
+
+        // 鍙嶅悜璺緞锛堥�嗚竟锛�
+        List<Point> pathRev = new ArrayList<>();
+        pathRev.add(start);
+        pathRev.add(s1.onEdge);
+        curr = s1.edgeIndex;
+        while (curr != s2.edgeIndex) {
+            pathRev.add(polygon.get(curr));
+            curr = (curr - 1 + n) % n;
+        }
+        pathRev.add(s2.onEdge);
+        pathRev.add(end);
+
+        return getPathLength(pathFwd) < getPathLength(pathRev) ? pathFwd : pathRev;
+    }
+
+    private static class SnapResult {
+        Point onEdge;
+        int edgeIndex;
+        SnapResult(Point p, int idx) { this.onEdge = p; this.edgeIndex = idx; }
+    }
+
+    // 璁$畻鐐瑰埌杈圭晫鏈�杩戠殑鎶曞奖鐐逛互鍙婃墍鍦ㄨ竟绱㈠紩
+    private static SnapResult snapToBoundary(Point p, List<Point> poly) {
+        double minD = Double.MAX_VALUE;
+        Point bestProj = p;
+        int bestIdx = -1;
+        for (int i = 0; i < poly.size(); i++) {
+            Point s = poly.get(i);
+            Point e = poly.get((i + 1) % poly.size());
+            double l2 = (s.x - e.x)*(s.x - e.x) + (s.y - e.y)*(s.y - e.y);
+            if (l2 == 0) {
+                double d = Math.hypot(p.x - s.x, p.y - s.y);
+                if (d < minD) { minD = d; bestProj = s; bestIdx = i; }
+                continue;
+            }
+            double t = ((p.x - s.x) * (e.x - s.x) + (p.y - s.y) * (e.y - s.y)) / l2;
+            t = Math.max(0, Math.min(1, t));
+            Point proj = new Point(s.x + t * (e.x - s.x), s.y + t * (e.y - s.y));
+            double d = Math.hypot(p.x - proj.x, p.y - proj.y);
+            if (d < minD) { minD = d; bestProj = proj; bestIdx = i; }
+        }
+        return new SnapResult(bestProj, bestIdx == -1 ? 0 : bestIdx);
+    }
+
+    private static boolean isSegmentSafe(Point p1, Point p2, List<Point> polygon) {
+        Point mid = new Point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2);
+        if (!isPointInPolygon(mid, polygon)) return false;
+        
+        for (int i = 0; i < polygon.size(); i++) {
+            Point a = polygon.get(i);
+            Point b = polygon.get((i + 1) % polygon.size());
+            if (isSamePoint(p1, a) || isSamePoint(p1, b) || isSamePoint(p2, a) || isSamePoint(p2, b)) continue;
+            if (segmentsIntersect(p1, p2, a, b)) return false;
+        }
+        return true;
+    }
+
+    private static boolean isSamePoint(Point a, Point b) {
+        return Math.abs(a.x - b.x) < 1e-4 && Math.abs(a.y - b.y) < 1e-4;
+    }
+
+    private static boolean segmentsIntersect(Point a, Point b, Point c, Point d) {
+        return ccw(a, c, d) != ccw(b, c, d) && ccw(a, b, c) != ccw(a, b, d);
+    }
+
+    private static boolean ccw(Point a, Point b, Point c) {
+        return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x);
+    }
+
+    private static boolean isPointInPolygon(Point p, List<Point> polygon) {
+        boolean result = false;
+        for (int i = 0, j = polygon.size() - 1; i < polygon.size(); j = i++) {
+            if ((polygon.get(i).y > p.y) != (polygon.get(j).y > p.y) &&
+                (p.x < (polygon.get(j).x - polygon.get(i).x) * (p.y - polygon.get(i).y) / (polygon.get(j).y - polygon.get(i).y) + polygon.get(i).x)) {
+                result = !result;
+            }
+        }
+        return result;
+    }
+
+    private static List<Point> getBoundaryPath(Point start, Point end, List<Point> polygon) {
+        int idx1 = getEdgeIndex(start, polygon);
+        int idx2 = getEdgeIndex(end, polygon);
+        
+        if (idx1 == -1 || idx2 == -1 || idx1 == idx2) {
+            return Arrays.asList(start, end);
+        }
+
+        List<Point> path1 = new ArrayList<>();
+        path1.add(start);
+        int curr = idx1;
+        while (curr != idx2) {
+            path1.add(polygon.get((curr + 1) % polygon.size()));
+            curr = (curr + 1) % polygon.size();
+        }
+        path1.add(end);
+
+        List<Point> pathRev = new ArrayList<>();
+        pathRev.add(start);
+        curr = idx1;
+        while (curr != idx2) {
+            pathRev.add(polygon.get(curr));
+            curr = (curr - 1 + polygon.size()) % polygon.size();
+        }
+        pathRev.add(polygon.get((idx2 + 1) % polygon.size()));
+        pathRev.add(end);
+        
+        return getPathLength(path1) < getPathLength(pathRev) ? path1 : pathRev;
+    }
+
+    private static double getPathLength(List<Point> path) {
+        double len = 0;
+        for (int i = 0; i < path.size() - 1; i++) {
+            len += Math.hypot(path.get(i).x - path.get(i+1).x, path.get(i).y - path.get(i+1).y);
+        }
+        return len;
+    }
+
+    private static int getEdgeIndex(Point p, List<Point> poly) {
+        int bestIdx = -1;
+        double minD = Double.MAX_VALUE;
+        for (int i = 0; i < poly.size(); i++) {
+            Point p1 = poly.get(i);
+            Point p2 = poly.get((i + 1) % poly.size());
+            double d = distToSegment(p, p1, p2);
+            if (d < minD) {
+                minD = d;
+                bestIdx = i;
+            }
+        }
+        // 鍙鎵惧埌鏈�杩戠殑杈瑰嵆鍙紝鏀惧闃堝�间互搴斿娴偣璇樊鍜屾棆杞彉褰�
+        // 濡傛灉璺濈杩囧ぇ锛堜緥濡傝秴杩�1绫筹級锛屽彲鑳界‘瀹炰笉鍦ㄨ竟鐣屼笂锛屼絾鍦ㄨ矾寰勮鍒掍笂涓嬫枃涓紝
+        // 杩欎簺鐐规槸鐢辨壂鎻忕嚎鐢熸垚鐨勶紝鐞嗚涓婁竴瀹氬湪杈圭晫涓婏紝鎵�浠ュ己鍒跺惛闄勬槸瀹夊叏鐨勩��
+        return minD < 1.0 ? bestIdx : -1;
+    }
+    
+    private static double distToSegment(Point p, Point s, Point e) {
+        double l2 = (s.x - e.x)*(s.x - e.x) + (s.y - e.y)*(s.y - e.y);
+        if (l2 == 0) return Math.hypot(p.x - s.x, p.y - s.y);
+        double t = ((p.x - s.x) * (e.x - s.x) + (p.y - s.y) * (e.y - s.y)) / l2;
+        t = Math.max(0, Math.min(1, t));
+        return Math.hypot(p.x - (s.x + t * (e.x - s.x)), p.y - (s.y + t * (e.y - s.y)));
     }
 
     private static Point rotatePoint(Point p, double angle) {
-        double cos = Math.cos(angle);
-        double sin = Math.sin(angle);
+        double cos = Math.cos(angle), sin = Math.sin(angle);
         return new Point(p.x * cos - p.y * sin, p.x * sin + p.y * cos);
     }
 
-    private static boolean isConvex(Point a, Point b, Point c) {
-        return (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x) >= 0;
-    }
-
-    private static boolean isPointInTriangle(Point p, Point a, Point b, Point c) {
-        double areaABC = Math.abs((a.x*(b.y-c.y) + b.x*(c.y-a.y) + c.x*(a.y-b.y))/2.0);
-        double areaPBC = Math.abs((p.x*(b.y-c.y) + b.x*(c.y-p.y) + c.x*(p.y-b.y))/2.0);
-        double areaPAC = Math.abs((a.x*(p.y-c.y) + p.x*(c.y-a.y) + c.x*(a.y-p.y))/2.0);
-        double areaPAB = Math.abs((a.x*(b.y-p.y) + b.x*(p.y-a.y) + p.x*(a.y-b.y))/2.0);
-        return Math.abs(areaABC - (areaPBC + areaPAC + areaPAB)) < 1e-6;
+    public static void ensureCounterClockwise(List<Point> points) {
+        double sum = 0;
+        for (int i = 0; i < points.size(); i++) {
+            Point p1 = points.get(i), p2 = points.get((i + 1) % points.size());
+            sum += (p2.x - p1.x) * (p2.y + p1.y);
+        }
+        if (sum > 0) Collections.reverse(points);
     }
 
     private static List<Point> parseCoordinates(String coordinates) {
         List<Point> points = new ArrayList<>();
-        String cleanStr = coordinates.replaceAll("[()\\[\\]{}]", "").trim();
-        String[] pairs = cleanStr.split(";");
+        String[] pairs = coordinates.split(";");
         for (String pair : pairs) {
-            pair = pair.trim();
-            if (pair.isEmpty()) continue;
             String[] xy = pair.split(",");
-            if (xy.length == 2) {
-                points.add(new Point(Double.parseDouble(xy[0].trim()), Double.parseDouble(xy[1].trim())));
-            }
+            if (xy.length == 2) points.add(new Point(Double.parseDouble(xy[0]), Double.parseDouble(xy[1])));
         }
+        if (points.size() > 1 && points.get(0).equals(points.get(points.size()-1))) points.remove(points.size()-1);
         return points;
     }
 
-    private static void ensureCounterClockwise(List<Point> points) {
-        double sum = 0;
-        for (int i = 0; i < points.size(); i++) {
-            Point p1 = points.get(i);
-            Point p2 = points.get((i + 1) % points.size());
-            sum += (p2.x - p1.x) * (p2.y + p1.y);
-        }
-        if (sum > 0) {
-            Collections.reverse(points);
-        }
-    }
-    
-    private static double distance(Point p1, Point p2) {
-        return Math.hypot(p1.x - p2.x, p1.y - p2.y);
-    }
-
-    // ==========================================
-    // 鍐呴儴鏁版嵁缁撴瀯
-    // ==========================================
-
     public static class Point {
         public double x, y;
         public Point(double x, double y) { this.x = x; this.y = y; }
-        @Override public String toString() { return String.format("%.2f,%.2f", x, y); }
+        @Override
+        public boolean equals(Object o) {
+            if (!(o instanceof Point)) return false;
+            Point p = (Point) o;
+            return Math.abs(x - p.x) < 1e-4 && Math.abs(y - p.y) < 1e-4;
+        }
     }
 
     public static class PathSegment {
-        public Point start;
-        public Point end;
-        public boolean isMowing;
-
-        public PathSegment(Point start, Point end, boolean isMowing) {
-            this.start = start;
-            this.end = end;
-            this.isMowing = isMowing;
-        }
-
-        @Override
-        public String toString() {
-            return String.format("[%s -> %s, 鍓茶崏:%b]", start, end, isMowing);
-        }
+        public Point start, end;
+        public boolean isMowing; // true: 鍓茶崏涓�, false: 绌鸿浇绉诲姩
+        public PathSegment(Point s, Point e, boolean m) { this.start = s; this.end = e; this.isMowing = m; }
     }
 }
\ No newline at end of file

--
Gitblit v1.10.0