f(3, 2) //9
function f(w, h) {
'use strict'
var len = w*h, result = 0
if (!(1 < len)) return -1
function dry() {
for (var j = 0; j < len; ++j) nc[no+j] = (0 < tc[to+j] && tc[to+j] < 6) ? tc[to+j]+1 : tc[to+j]
for (; j < len+3; ++j) nc[no+j] = tc[to+j]
}
function paint(x, y) {
dry()
nc[no+x+w*y] = 1
if(++nc[no+len+2] == len) result = turn
nl++, no+=len+3
}
function move(x, y) {
dry()
nc[no+len] = x, nc[no+len+1] = y
nl++, no+=len+3
}
function move_paint(x, y) {
v++
if (tc[to+x+y*w] == 0) {move(x, y); paint(x, y)}
else if (tc[to+x+y*w] == 6) move(x, y)
else v--
}
var tl = 0, nl = 1, tc = [], nc = new Uint8Array(len+3)
for (var turn = 1; ; turn++) {
tl = nl, nl = 0, tc = nc, nc = new Uint8Array(tl*(len+3)*4)
for (var no = 0, i = 0; i < tl ;i++) {
var to = i*(len+3), v = 0, x = tc[to+len], y = tc[to+len+1]
if (0 < x) move_paint(x-1, y)
if (x < w-1) move_paint(x+1, y)
if (0 < y) move_paint(x, y-1)
if (y < h-1) move_paint(x, y+1)
if (v == 0) move(x, y)
if (result > 0) return result
}
}
return -1
}
ZigzLCAyKSAvLzkKCgpmdW5jdGlvbiBmKHcsIGgpIHsKICAndXNlIHN0cmljdCcKCiAgdmFyIGxlbiA9IHcqaCwgcmVzdWx0ID0gMAoKICBpZiAoISgxIDwgbGVuKSkgcmV0dXJuIC0xCgogIGZ1bmN0aW9uIGRyeSgpIHsKICAgIGZvciAodmFyIGogPSAwOyBqIDwgbGVuOyArK2opIG5jW25vK2pdID0gKDAgPCB0Y1t0bytqXSAmJiB0Y1t0bytqXSA8IDYpID8gdGNbdG8ral0rMSA6IHRjW3RvK2pdCiAgICBmb3IgKDsgaiA8IGxlbiszOyArK2opIG5jW25vK2pdID0gdGNbdG8ral0KICB9CgogIGZ1bmN0aW9uIHBhaW50KHgsIHkpIHsKICAgIGRyeSgpCiAgICBuY1tubyt4K3cqeV0gPS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