/**
1888 · Shortest Path in Matrix
Algorithms
Medium
Accepted Rate
44%
DescriptionSolutionNotesDiscussLeaderboard
Description
Given the matrix of M rows and N columns, 0 represents empty space, - 1 represents obstacle, and 1 represents target points (there are multiple target points).
For each empty space, mark the direction from the point to reach the target point with the shortest distance.
If starting up, you should mark the point as 2. if starting down , you should mark the point as 3. if starting left , you should mark the point as 4. if starting right , you should mark the point as 5.
The priority of direction is up, down, left and right from big to small, that is, if you can reach the target point with the shortest distance from a point up or down, you are supposed to start up.
Returns the matrix after marking.
0<m,n<1000
Example
Example 1:
input:
[[1,0,1],[0,0,0],[1,0,0]]
output:
[[1,4,1],[2,2,2],[1,4,2]]
Tags
https://blog.csdn.net/qq_46105170/article/details/109219162
https://www.lintcode.com/problem/1888/
*/
这题没写出来,没有用golang处理好Queue数据结构,语法有错误,有懂得的高人可以指点下
/**
队列:
基本操作是入队(Enqueue),在表的末端插入一个元素
出队(Dequeue),删除(或返回)在表头的元素
*/
type Item interface {}
// 队列结构体
type Queue struct {
Items []Item
}
type IQueue interface {
New() Queue
Enqueue(t Item)
Dequeue(t Item)
IsEmpty() bool
Size() int
}
// 新建
func (q *Queue)New() *Queue {
q.Items = []Item{}
return q
}
// 入队
func (q *Queue) Enqueue(data Item) {
q.Items = append(q.Items, data)
}
// 出队
func (q *Queue) Dequeue() *Item {
// 由于是先进先出,0为队首
item := q.Items[0]
q.Items = q.Items[1: len(q.Items)]
return &item
}
// 队列是否为空
func (q *Queue) IsEmpty() bool {
return len(q.Items) == 0
}
// 队列长度
func (q *Queue) Size() int {
return len(q.Items)
}
var q Queue
func initQueue() *Queue {
if q.Items == nil{
q = Queue{}
q.New()
}
return &q
}
/**
* @param grid: the input matrix
* @return: the new matrix
*/
func shortestPath (grid [][]int) [][]int {
// write your code here
var m int = len(grid)
var n int = len(grid[0])
var steps = make([][]int, m)
for i := 0; i < m; i++ {
steps[i] = make([]int, n)
}
var queue *Queue = initQueue()
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 1 {
queue.Enqueue([]int{i, j})
}
}
}
var step int = 0
var d []int = []int{1, 0, -1, 0, 1}
var mark []int = []int{2, 5, 3, 4}
for {
if queue.IsEmpty() {
break
}
step += 1
var size int = queue.Size()
for i := 0; i < size; i++ {
var cur = queue.Dequeue()
for j := 0; j < 4; j++ {
var nextX int = cur[0] + d[j]
var nextY int = cur[1] + d[j + 1]
if inBound(nextX, nextY, grid) {
if grid[nextX][nextY] == 0 {
grid[nextX][nextY] = mark[j]
steps[nextX][nextY] = step
queue.Enqueue([]int{nextX, nextY})
} else {
if steps[nextX][nextY] == step {
grid[nextX][nextY] = Min(grid[nextX][nextY], mark[j])
}
}
}
}
}
}
return grid
}
func inBound(x, y int, grid [][]int) bool {
return 0 <= x && x < len(grid) && 0 <= y && y < len(grid[0])
}
func Min(a, b int) int {
if a < b {
return a
}
return b
}