From 535e90ca61329e9bf756cceba4b3824746e8b1f9 Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Wed, 14 Jun 2023 12:31:48 +0800 Subject: [PATCH] =?UTF-8?q?:sparkles:=20=E6=94=AF=E6=8C=81=E9=80=9A?= =?UTF-8?q?=E8=BF=87=E4=B8=89=E4=B8=AA=E6=96=B0=E5=87=BD=E6=95=B0GetAdjace?= =?UTF-8?q?ntTranslatePos=E3=80=81GetAdjacentDiagonalsPos=E3=80=81GetAdjac?= =?UTF-8?q?entPos=E8=8E=B7=E5=8F=96=E4=B8=8A=E4=B8=8B=E5=B7=A6=E5=8F=B3?= =?UTF-8?q?=E5=8F=8A=E5=AF=B9=E8=A7=92=E7=BA=BF=E6=9C=80=E5=A4=9A=E5=85=AB?= =?UTF-8?q?=E4=B8=AA=E6=96=B9=E5=90=91=E7=9A=84=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/g2d/g2d.go | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/utils/g2d/g2d.go b/utils/g2d/g2d.go index bcff311..cd85681 100644 --- a/utils/g2d/g2d.go +++ b/utils/g2d/g2d.go @@ -33,8 +33,8 @@ func GetAdjacentCoordinates[T any](matrix [][]T, x, y int) (result [][2]int) { return } -// GetAdjacentCoordinatesWithPos 获取一个连续位置的矩阵中,特定位置相邻的最多四个方向的坐标 -func GetAdjacentCoordinatesWithPos[T any](matrix []T, width, pos int) (result []int) { +// GetAdjacentTranslatePos 获取一个连续位置的矩阵中,特定位置相邻的最多四个平移方向(上下左右)的位置 +func GetAdjacentTranslatePos[T any](matrix []T, width, pos int) (result []int) { size := len(matrix) currentRow := pos / width if up := pos - width; up >= 0 { @@ -52,6 +52,30 @@ func GetAdjacentCoordinatesWithPos[T any](matrix []T, width, pos int) (result [] return } +// GetAdjacentDiagonalsPos 获取一个连续位置的矩阵中,特定位置相邻的对角线最多四个方向的位置 +func GetAdjacentDiagonalsPos[T any](matrix []T, width, pos int) (result []int) { + size := len(matrix) + currentRow := pos / width + if topLeft := pos - width - 1; topLeft >= 0 && currentRow-1 == (topLeft/width) { + result = append(result, topLeft) + } + if topRight := pos - width + 1; topRight >= 0 && currentRow-1 == (topRight/width) { + result = append(result, topRight) + } + if bottomLeft := pos + width - 1; bottomLeft < size && currentRow+1 == (bottomLeft/width) { + result = append(result, bottomLeft) + } + if bottomRight := pos + width + 1; bottomRight < size && currentRow+1 == (bottomRight/width) { + result = append(result, bottomRight) + } + return +} + +// GetAdjacentPos 获取一个连续位置的矩阵中,特定位置相邻的最多八个方向的位置 +func GetAdjacentPos[T any](matrix []T, width, pos int) (result []int) { + return append(GetAdjacentTranslatePos(matrix, width, pos), GetAdjacentDiagonalsPos(matrix, width, pos)...) +} + // CoordinateToPos 将坐标转换为二维数组的顺序位置坐标 // - 需要确保x的取值范围必须小于width,或者将会得到不正确的值 func CoordinateToPos(width, x, y int) int {