Ruby Accepted Solution
I had few runs of here-and-there small optimizations which finally brought me to the AC Solution.\n\nThe main idea is: check all the skip cases for the cell bef
I had few runs of here-and-there small optimizations which finally brought me to the AC Solution.\n\nThe main idea is: check all the skip cases for the cell before adding it to the queue.\n\n```\ndef cut_off_tree(forest)\n    h = []\n\n    for i in 0..forest.size - 1\n      for j in 0..forest[0].size - 1\n        if forest[i][j] > 1\n          h.push(forest[i][j])\n        end\n      end\n    end\n\n    h.sort!\n\n    helper(forest, 0, 0, h, 0)\nend\n\ndef helper(forest, istart, jstart, h, n)\n  return if n == h.size\n  target = h[n]\n  q = [[istart, jstart]]\n\n  step = 0\n  visited = Array.new(forest.size) { Array.new(forest[0].size, 0) }\n  while !q.empty?\n    q.size.times do\n      i, j = q.shift\n\n      if forest[i][j] == target\n        forest[i][j] = 1\n        next_search = helper(forest, i, j, h, n + 1)\n        return -1 if next_search == -1\n        return step + next_search.to_i\n      else\n        if i - 1 >= 0 && forest[i - 1][j] > 0 && visited[i - 1][j] == 0\n          q.push([i - 1, j])\n          visited[i - 1][j] = 1\n        end\n        if i + 1 < forest.size && forest[i + 1][j] > 0 && visited[i + 1][j] == 0\n          q.push([i + 1, j])\n          visited[i + 1][j] = 1\n        end\n        if j - 1 >= 0 && forest[i][j - 1] > 0 && visited[i][j - 1] == 0\n          q.push([i, j - 1])\n          visited[i][j - 1] = 1\n        end\n        if j + 1 < forest[0].size && forest[i][j + 1] > 0 && visited[i][j + 1] == 0\n          q.push([i, j + 1])\n          visited[i][j + 1] = 1\n        end\n      end\n    end\n\n    step += 1\n  end\n\n  -1\nend
[]