Simple BFS - Go
Intuition\n Describe your first thoughts on how to solve this problem. \n\nThe idea is to find minimum steps between each consecutive numbers on the grid. \n\nA
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe idea is to find minimum steps between each consecutive numbers on the grid. \n\nA simple BFS from 1 number to the very next number works. If such a path doesn\'t exist, return -1\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nFind the consecutive numbers from the grid which are greater than 1s. \n\nSort the list to traverse on them based on their ordering.\n\nDo BFS on each pair, and count steps. add the steps to global sum.\n\nOn catch is how to handle the scenario that you always start from 0, 0 and the first entry in the list may not be 0, 0. To solve this. start from 0,0 by default and if such a 0, 0 already exist at start BFS will give 0. [BFS gives -1 if path not possible.]\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\ntype Coord struct {\n\tx   int\n\ty   int\n\tval int\n}\n\nfunc cutOffTree(forest [][]int) int {\n\n\tR := len(forest)\n\tC := len(forest[0])\n\n\ttrees := []Coord{}\n\n\tfor i := range forest {\n\t\tfor j := range forest[i] {\n\t\t\tif forest[i][j] > 1 {\n\t\t\t\ttrees = append(trees, Coord{i, j, forest[i][j]})\n\t\t\t}\n\t\t}\n\t}\n\n\tsort.Slice(trees, func(i, j int) bool {\n\t\treturn trees[i].val < trees[j].val\n\t})\n\n\tpaths := [][]int{\n\t\t{1, 0},\n\t\t{0, 1},\n\t\t{0, -1},\n\t\t{-1, 0},\n\t}\n\n\tbfs := func(sx, sy, dx, dy int) int {\n\t\trow := R\n\t\tcol := C\n\t\tvisited := make([][]bool, row)\n\t\trows := make([]bool, row*col)\n\t\tfor i := range visited {\n\t\t\tvisited[i] = rows[i*C : (i+1)*C]\n\t\t}\n\n\t\tq := [][3]int{}\n\t\tq = append(q, [3]int{sx, sy, 0})\n\t\tvisited[sx][sy] = true\n\n\t\tfor len(q) > 0 {\n\t\t\tcurr := q[0]\n\t\t\tq = q[1:]\n\n\t\t\tif curr[0] == dx && curr[1] == dy {\n\t\t\t\treturn curr[2]\n\t\t\t}\n\n\t\t\tfor _, p := range paths {\n\t\t\t\tnx := p[0] + curr[0]\n\t\t\t\tny := p[1] + curr[1]\n\n\t\t\t\tif nx >= 0 && nx < R && ny >= 0 && ny < C && !visited[nx][ny] && forest[nx][ny] != 0 {\n\t\t\t\t\tvisited[nx][ny] = true\n\t\t\t\t\tq = append(q, [3]int{nx, ny, curr[2] + 1})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn -1\n\t}\n\n\tcount := 0\n\tstart := Coord{x: 0, y: 0}\n\tfor i := 0; i < len(trees); i++ {\n\t\tdist := bfs(start.x, start.y, trees[i].x, trees[i].y)\n\t\tif dist == -1 {\n\t\t\treturn -1\n\t\t}\n\t\tstart.x = trees[i].x\n\t\tstart.y = trees[i].y\n\t\tcount += dist\n\t}\n\treturn count\n}\n```
['Go']