結果
| 問題 |
No.367 ナイトの転身
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2020-05-05 00:28:05 |
| 言語 | Lua (LuaJit 2.1.1734355927) |
| 結果 |
AC
|
| 実行時間 | 98 ms / 2,000 ms |
| コード長 | 2,936 bytes |
| コンパイル時間 | 28 ms |
| コンパイル使用メモリ | 6,688 KB |
| 実行使用メモリ | 17,152 KB |
| 最終ジャッジ日時 | 2024-06-25 06:23:13 |
| 合計ジャッジ時間 | 1,852 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 27 |
ソースコード
local h, w = io.read("*n", "*n", "*l")
local map = {}
local inf = 1000000007
local len = {}
local spos, gpos = 0, 0
for i = 1, h do
local s = io.read()
for j = 1, w do
local ss = s:sub(j, j)
local idx = (i - 1) * w + j
map[idx] = false
if ss == "S" then
spos = idx
elseif ss == "G" then
gpos = idx
elseif ss == "R" then
map[idx] = true
end
end
end
for i = 1, h * w * 2 do len[i] = inf end
local taskstate = {}
for i = 1, h * w * 2 do taskstate[i] = false end
local tasks = {}
local tasknum = 0
local done = 0
local tasklim = h * w * 2
local function addtask(mixidx)
if not taskstate[mixidx] then
taskstate[mixidx] = true
tasknum = tasknum + 1
local taskidx = tasknum % tasklim
if taskidx == 0 then taskidx = tasklim end
tasks[taskidx] = mixidx
end
end
local function walk(src, dst, knight)
local mixsrc = src
if knight then
mixsrc = mixsrc + h * w
end
local mixdst = dst
if knight and not map[dst] then
mixdst = mixdst + h * w
elseif not knight and map[dst] then
mixdst = mixdst + h * w
end
if len[mixsrc] + 1 < len[mixdst] then
len[mixdst] = len[mixsrc] + 1
addtask(mixdst)
end
end
len[spos + h * w] = 0
addtask(spos + h * w)
while done < tasknum do
done = done + 1
local taskidx = done % tasklim
if taskidx == 0 then taskidx = tasklim end
local mixidx = tasks[taskidx]
taskstate[mixidx] = false
local knight = h * w < mixidx
local idx = mixidx
if knight then idx = idx - h * w end
if knight then
if 2 * w < idx then
if 1 < w then
if idx % w ~= 0 then walk(idx, idx + 1 - w - w, true) end
if idx % w ~= 1 then walk(idx, idx - 1 - w - w, true) end
end
end
if idx <= (h - 2) * w then
if 1 < w then
if idx % w ~= 0 then walk(idx, idx + 1 + w + w, true) end
if idx % w ~= 1 then walk(idx, idx - 1 + w + w, true) end
end
end
if w < idx then
if 2 < w then
if idx % w ~= 0 and idx % w ~= (w - 1) then
walk(idx, idx + 2 - w, true)
end
if idx % w ~= 1 and idx % w ~= 2 then
walk(idx, idx - 2 - w, true)
end
end
end
if idx <= (h - 1) * w then
if 2 < w then
if idx % w ~= 0 and idx % w ~= (w - 1) then
walk(idx, idx + 2 + w, true)
end
if idx % w ~= 1 and idx % w ~= 2 then
walk(idx, idx - 2 + w, true)
end
end
end
else
if w < idx then
if 1 < w then
if idx % w ~= 0 then walk(idx, idx + 1 - w, false) end
if idx % w ~= 1 then walk(idx, idx - 1 - w, false) end
end
end
if idx <= (h - 1) * w then
if 1 < w then
if idx % w ~= 0 then walk(idx, idx + 1 + w, false) end
if idx % w ~= 1 then walk(idx, idx - 1 + w, false) end
end
end
end
end
local ret = math.min(len[gpos], len[gpos + h * w])
print(inf <= ret and -1 or ret)