Skip to content

Instantly share code, notes, and snippets.

@Zhomart
Created August 28, 2017 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zhomart/17de2c1008540d29ec64615c5e5f3c95 to your computer and use it in GitHub Desktop.
Save Zhomart/17de2c1008540d29ec64615c5e5f3c95 to your computer and use it in GitHub Desktop.
  1. Try going to each 8 direction, from queens position, until you face obstacle and just count
  2. I used set to check if movement hit the ostacle
defmodule Solution do

  def count(_, qr, qc, _, _) when qr == 0 or qc == 0, do: 0
  def count(n, qr, qc, _, _) when qr == n+1 or qc == n+1, do: 0
  def count(n, qr, qc, obs, speed) do
    if MapSet.member?(obs, {qr, qc}) do # if obstacle
      0
    else
      count(n, qr + elem(speed, 0), qc + elem(speed, 1), obs, speed) + 1
    end
  end

end

[n, k] = IO.gets("") |> String.strip |> String.split(" ") |> Enum.map(&String.to_integer/1)
[qr, qc] = IO.gets("") |> String.strip |> String.split(" ") |> Enum.map(&String.to_integer/1)
obstacles = if k > 0 do
  (for _ <- 0..k-1, do: IO.gets("") |> String.strip)
  |> Enum.map(fn line -> line |> String.split(" ") |> Enum.map(&String.to_integer/1) end)
else
  []
end

obs = obstacles |> Enum.reduce(MapSet.new, fn ([r, c], obs) -> MapSet.put(obs, {r, c}) end)

speeds = for r <- [-1, 0, 1], c <- [-1, 0, 1], r !=0 || c != 0, do: {r, c}
counts = speeds |> Enum.map(fn e -> Solution.count(n, qr, qc, obs, e) - 1 end)

IO.puts Enum.sum(counts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment