# Go - 如何排除溢出矩阵的坐标

``````package main

import "fmt"

func Input(y, x int) []int {
matrix := [][]int{
[]int{0, 2, 3},
[]int{2, 3, 1},
[]int{8, 7, 4},
[]int{3, 2, 1},
}
k := []int{matrix[y+1][x], matrix[y-1][x], matrix[y][x+1], matrix[y][x-1]}
for _, z := range k {
if z == -1 { //error
return append(k[z:], k[:z-1]...)
}
}
return k
}
func main() {
fmt.Println(Input(0, 0))
}
``````

## 推荐答案

``````(y-1,x), (y+1, x), (y,x-1), (y,x+1)
``````

``````var result []int

if y > 0 {
result = append(result, matrix[y-1][x])
}
if y < len(matrix)-1 {
result = append(result, matrix[y+1][x])
}
if x > 0 {
result = append(result, matrix[y][x-1])
}
if x < len(matrix[y])-1 {
result = append(result, matrix[y][x+1])
}

return result
``````

``````[2 2]
``````

``````var result []int
if y < 0 || y >= len(matrix) || x < 0 || x >= len(matrix[y]) {
return result
}
``````

``````var neighbors = [][]int{
{-1, 0},
{1, 0},
{0, -1},
{0, 1},
}
``````

``````var result []int
for _, neighbor := range neighbors {
iy, ix := y+neighbor[0], x+neighbor[1]
if iy < 0 || iy >= len(matrix) || ix < 0 || ix >= len(matrix[iy]) {
continue
}
result = append(result, matrix[iy][ix])
}

return result
``````

Go Playground号上试试这个.