Some people leave the lights at their workplaces on when they leave that is a waste of resources. As a hausmeister of DHBW, Sagheer waits till all students and professors leave the university building, then goes and turns all the lights off.

The building consists of n floors with stairs at the left and the right sides. Each floor has m rooms on the same line with a corridor that connects the left and right stairs passing by all the rooms. In other words, the building can be represented as a rectangle with n rows and m + 2 columns, where the first and the last columns represent the stairs, and the m columns in the middle represent rooms.

Sagheer is standing at the ground floor at the left stairs. He wants to turn all the lights off in such a way that he will not go upstairs until all lights in the floor he is standing at are off. Of course, Sagheer must visit a room to turn the light there off. It takes one minute for Sagheer to go to the next floor using stairs or to move from the current room/stairs to a neighboring room/stairs on the same floor. It takes no time for him to switch the light off in the room he is currently standing in. Help Sagheer find the minimum total time to turn off all the lights.

Note that Sagheer does not have to go back to his starting position, and he does not have to visit rooms where the light is already switched off.


-----Input-----

The first line contains two integers n and m (1 ≤ n ≤ 15 and 1 ≤ m ≤ 100) — the number of floors and the number of rooms in each floor, respectively.

The next n lines contains the building description. Each line contains a binary string of length m + 2 representing a floor (the left stairs, then m rooms, then the right stairs) where 0 indicates that the light is off and 1 indicates that the light is on. The floors are listed from top to bottom, so that the last line represents the ground floor.

The first and last characters of each string represent the left and the right stairs, respectively, so they are always 0.


-----Output-----

Print a single integer — the minimum total time needed to turn off all the lights.


-----Examples-----
Input
2 2
0010
0100

Output
5

Input
3 4
001000
000010
000010

Output
12

Input
4 3
01110
01110
01110
01110

Output
18



-----Note-----

In the first example, Sagheer will go to room 1 in the ground floor, then he will go to room 2 in the second floor using the left or right stairs.

In the second example, he will go to the fourth room in the ground floor, use right stairs, go to the fourth room in the second floor, use right stairs again, then go to the second room in the last floor.

In the third example, he will walk through the whole corridor alternating between the left and right stairs at each floor.

Difficulty: MEDIUM_HARD

Solutions:
(n, m) = map(int, input().split())
p = [input() for y in range(n)][::-1]
l = r = d = 0
i = j = 0
for (y, t) in enumerate(p):
	if '1' in t:
		(l, r) = (min(l - i, r - j) + 2 * m + 2, min(l + i, r + j))
		(i, j) = (t.find('1'), t.rfind('1'))
		(l, r, d) = (l - i, r + j, y)
print(min(l, r) + d)


from sys import stdin as fin

def f(i, csum, csl=True):
	global num_f, l_a, r_a, minv
	(l, r) = (l_a[i], r_a[i])
	if i == num_f:
		csum += r if csl else l
		minv = min(minv, csum)
	else:
		f(i + 1, csum + m + 2, not csl)
		f(i + 1, csum + (r if csl else l) * 2 + 1, csl)
(n, m) = map(int, fin.readline().split())
arr = [list((int(sym) for sym in fin.readline().strip())) for i in range(n)]
csl = True
cnt = 0
border = 0
for i in range(n):
	if 1 in arr[i]:
		break
	else:
		border += 1
(l_a, r_a) = ([], [])
num_f = -1
minv = float('inf')
for i in range(n - 1, border - 1, -1):
	if 1 in arr[i]:
		l = arr[i].index(1)
		r = list(reversed(arr[i])).index(1)
		l = m + 2 - l - 1
		r = m + 2 - r - 1
	else:
		l = r = 0
	l_a.append(l)
	r_a.append(r)
	num_f += 1
	continue
if num_f > -1:
	f(0, 0)
	print(minv)
else:
	print(0)


def coun(pref):
	now = 0
	for i in range(n):
		pos = pref[i]
		if pos == 'l':
			if i < n - 1 and sum(check[i + 1:]) > 0:
				now += 1
				if '1' in mat[i]:
					if pref[i + 1] == 'r':
						now += m + 1
					else:
						now += 2 * mat[i].rfind('1')
				elif pref[i + 1] == 'r':
					now += m + 1
			elif '1' in mat[i]:
				now += mat[i].rfind('1')
		elif i < n - 1 and sum(check[i + 1:]) > 0:
			now += 1
			if '1' in mat[i]:
				if pref[i + 1] == 'l':
					now += m + 1
				else:
					now += 2 * (m + 1 - mat[i].find('1'))
			elif pref[i + 1] == 'l':
				now += m + 1
		elif '1' in mat[i]:
			now += m + 1 - mat[i].find('1')
	return now

def gen(pref):
	global ans
	if len(pref) == n:
		ans = min(ans, coun(pref))
		return
	gen(pref + 'l')
	gen(pref + 'r')
(n, m) = map(int, input().split())
mat = [0] * n
for i in range(n):
	mat[i] = input()
mat.reverse()
check = [0] * n
for i in range(n):
	check[i] = mat[i].count('1')
ans = 1000000000
gen('l')
print(ans)


(n, m) = list(map(int, input().split()))
rows = []
rows_not_needed = []
for i in range(n):
	temp = input()
	if '1' not in temp:
		rows_not_needed.append(i)
		continue
	rows.append(temp)
n = n - len(rows_not_needed)
if n == 0:
	print(0)
	exit()
dp = [[0 for _ in range(2)] for _ in range(n)]
l = [0 for _ in range(n)]
r = [0 for _ in range(n)]
for i in range(0, n):
	for j in range(0, m + 2):
		if rows[i][j] == '1':
			r[i] = j
	for j in range(m + 1, -1, -1):
		if rows[i][j] == '1':
			l[i] = j
dp[0][0] = r[0]
dp[0][1] = m + 1 - l[0]
for i in range(1, n):
	dp[i][0] = min(r[i] + m + 1 - r[i] + 1 + dp[i - 1][1], r[i] + r[i] + 1 + dp[i - 1][0])
	dp[i][1] = min(m + 1 - l[i] + l[i] + 1 + dp[i - 1][0], m + 1 - l[i] + m + 1 - l[i] + 1 + dp[i - 1][1])
for i in range(0, len(rows_not_needed)):
	if rows_not_needed[i] != i:
		dp[n - 1][0] += 1
print(dp[n - 1][0])


def minimum(floor, j, s, n, m):
	if s == []:
		return 0
	if floor == 0:
		if j == 0:
			return s[floor].rfind('1')
		else:
			return m + 1 - s[floor].find('1')
	if j == 0:
		return min(2 * s[floor].rfind('1') + 1 + minimum(floor - 1, 0, s, n, m), m + 2 + minimum(floor - 1, m + 1, s, n, m))
	else:
		return min(2 * (m + 1 - s[floor].find('1')) + 1 + minimum(floor - 1, m + 1, s, n, m), m + 2 + minimum(floor - 1, 0, s, n, m))
inp = input().split()
n = int(inp[0])
m = int(inp[1])
s = []
for i in range(n):
	s.append(input())
counter = 0
while s != []:
	if s[0].find('1') == -1:
		counter += 1
		s.pop(0)
	else:
		break
counter2 = 0
s2 = []
for val in s:
	if val.find('1') == -1:
		counter2 += 1
	else:
		s2.append(val)
print(minimum(n - 1 - counter - counter2, 0, s2, n, m) + counter2)


(n, m) = map(int, input().split())
a = [''] * n
for i in range(n):
	a[n - i - 1] = input()
(res, ll, rr, k, l, r) = (0, 0, 0, 0, 0, 0)
for s in a:
	(i, l, r) = (0, 0, 0)
	for z in s:
		if z == '1':
			if l == 0:
				l = m - i + 1
			r = i
		i += 1
	if k == 0:
		(p, q, rr) = (ll + 2 * r, ll + m + 1, m + 1)
	else:
		(p, q) = (min(ll + 2 * r, rr + m + 1), min(ll + m + 1, rr + 2 * l))
	if l or r:
		res = min(ll + r + k, rr + l + k)
	k += 1
	(ll, rr) = (p, q)
print(res)


from collections import Counter
import sys

def left_time(floor):
	light_counter = Counter(floor)
	if light_counter['1'] == 0:
		return 0
	else:
		last_light_search = 1
		while last_light_search <= len(floor):
			if floor[-last_light_search] == '1':
				return (len(floor) - last_light_search) * 2
				break
			else:
				last_light_search += 1

def right_time(floor):
	light_counter = Counter(floor)
	if light_counter['1'] == 0:
		return 0
	else:
		last_light_search = 0
		while True:
			if floor[last_light_search] == '1':
				return (len(floor) - last_light_search - 1) * 2
				break
			else:
				last_light_search += 1
(floors_nr, rooms_nr) = (int(x) for x in input().split())
building_scheme = []
worth_counting_flag = False
for i in range(floors_nr):
	floor_i = input()
	c = Counter(floor_i)
	if not worth_counting_flag and c['1'] > 0:
		worth_counting_flag = True
	if worth_counting_flag:
		building_scheme.append(floor_i)
if len(building_scheme) == 0:
	print(0)
	sys.exit()
optimal_time = [(-1, 10000)]
last_floor = building_scheme[0]
building_scheme = building_scheme[1:]
for floor in building_scheme[::-1]:
	(prefix_left, prefix_right) = optimal_time[-1]
	keep_right_left = rooms_nr + 1 + prefix_left + 1
	keep_right_right = right_time(floor) + prefix_right + 1
	keep_right = min(keep_right_left, keep_right_right)
	keep_left_left = left_time(floor) + prefix_left + 1
	keep_left_right = rooms_nr + 1 + prefix_right + 1
	keep_left = min(keep_left_left, keep_left_right)
	optimal_time.append((keep_left, keep_right))
last_floor_time = min(optimal_time[-1][0] + 1 + left_time(last_floor) // 2, optimal_time[-1][1] + 1 + right_time(last_floor) // 2)
print(last_floor_time)


(floors, rooms) = map(int, input().split())
m = []
for i in range(floors):
	m.append(input())

def solve(current, f=1, cost=0, lastFloor=0):
	if f == lastFloor:
		return cost
	currentFloor = floors - f - 1
	(first, last) = (m[currentFloor - 1].find('1'), m[currentFloor - 1].rfind('1'))
	if first == -1:
		return solve(current, f + 1, cost + 1, lastFloor)
	return min(solve(last, f + 1, cost + current + last + 1, lastFloor), solve(first, f + 1, cost + (rooms + 1 - current) + 1 + (rooms + 1 - first), lastFloor))
lastFloor = -1
for i in range(floors):
	if '1' in m[i]:
		lastFloor = floors - i - 1
		break
if lastFloor == -1:
	print('0')
elif floors == 1:
	print(m[0].rfind('1'))
else:
	for (i, x) in enumerate(reversed(m)):
		pos = x.rfind('1')
		if pos != -1:
			print(solve(pos, i, pos + i, lastFloor))
			break


def first_one(row):
	for i in range(len(row)):
		if row[i] == '1':
			return i
	return len(row) - 1

def last_one(row):
	for i in range(len(row) - 1, -1, -1):
		if row[i] == '1':
			return i
	return 0

def left_score(i):
	la = last_one(l[i])
	s = la
	right_pur = m + 1 - la + 1 + scores[i - 1][1]
	left_pur = la + 1 + scores[i - 1][0]
	s += min(right_pur, left_pur)
	return s

def right_score(i):
	la = first_one(l[i])
	s = m + 1 - la
	right_pur = m + 1 - la + 1 + scores[i - 1][1]
	left_pur = la + 1 + scores[i - 1][0]
	s += min(right_pur, left_pur)
	return s
(n, m) = list(map(int, input().split()))
l = [input() for i in range(n)]
if n == 1:
	print(last_one(l[0]))
else:
	i = 0
	while l != [] and '1' not in l[0]:
		del l[0]
		n -= 1
	if n == 1:
		print(last_one(l[0]))
	elif n == 0:
		print(0)
	else:
		scores = [[last_one(l[0]), m + 1 - first_one(l[0])]]
		for i in range(1, n - 1):
			scores.append([left_score(i), right_score(i)])
		print(left_score(n - 1))


Inf = int(1000000000.0 + 7)
[n, m] = list(map(int, input().split()))
bld = list()
for i in range(n):
	bld.append(input())
bld.reverse()
lef = [m + 1 for i in range(n)]
rig = [0 for i in range(n)]
last = -1
for i in range(n):
	for j in range(m + 2):
		if bld[i][j] == '1':
			lef[i] = min(lef[i], j)
			rig[i] = max(rig[i], j)
			last = max(last, i)
dp = [[Inf for j in range(2)] for i in range(n)]
dp[0][0] = 0
for i in range(last):
	dp[i + 1][0] = min(dp[i + 1][0], dp[i][1] + m + 1 + 1)
	dp[i + 1][0] = min(dp[i + 1][0], dp[i][0] + 2 * rig[i] + 1)
	dp[i + 1][1] = min(dp[i + 1][1], dp[i][0] + m + 1 + 1)
	dp[i + 1][1] = min(dp[i + 1][1], dp[i][1] + 2 * (m + 1 - lef[i]) + 1)
if last == -1:
	print('0')
	exit(0)
elif last == 0:
	res = rig[0]
else:
	res = min(dp[last][0] + rig[last], dp[last][1] + (m + 1 - lef[last]))
print(res)


(n, m) = map(int, input().split())
a = []
for i in range(n):
	a.append(input())
l = 0
r = INF = 100000
h = 0
while h < n:
	if a[h] == '0' * (m + 2):
		h += 1
	else:
		break
if h != n:
	for i in range(n - 1, h, -1):
		x = INF
		y = 0
		for j in range(m + 2):
			if a[i][j] == '1':
				x = min(x, j)
				y = max(y, j)
		if x != INF:
			ll = min(l + y * 2, r + m + 1)
			rr = min(l + m + 1, r + (m + 1 - x) * 2)
			l = ll
			r = rr
	x = INF
	y = 0
	for j in range(m + 2):
		if a[h][j] == '1':
			x = min(x, j)
			y = max(y, j)
	ans = min(l + y, r + (m + 1 - x))
	print(ans + n - 1 - h)
else:
	print(0)


import sys
inf = float('inf')
ans = inf

def solve():
	(n, m) = map(int, input().split())
	s = [None] * n
	for i in range(n - 1, -1, -1):
		s[i] = [int(j) for j in input()]
	e = [any(si) for si in s]
	es = e[:] + [False]
	for i in range(n - 1, -1, -1):
		es[i] |= es[i + 1]
	if not es[0]:
		print(0)
	elif es[0] and (not es[1]):
		k = m + 1 - s[0][::-1].index(1)
		print(k)
	else:
		lim = 0
		for i in range(n + 1):
			if not es[i]:
				lim = i - 1
				break
		if not e[0]:
			left = 0
			right = m + 1
		else:
			kr = m + 1 - s[0][::-1].index(1)
			left = 2 * kr
			right = m + 1
		for i in range(1, lim):
			if not e[i]:
				(left, right) = (min(left + 1, right + m + 2), min(right + 1, left + m + 2))
			else:
				kr = m + 1 - s[i][::-1].index(1)
				kl = s[i].index(1)
				(left, right) = (min(left + 1 + 2 * kr, right + m + 2), min(right + 1 + 2 * (m + 1 - kl), left + m + 2))
		kr = m + 1 - s[lim][::-1].index(1)
		kl = s[lim].index(1)
		ans = min(left + 1 + kr, right + 1 + m + 1 - kl)
		print(ans)

def __starting_point():
	solve()
__starting_point()


(n, m) = map(int, input().split())
l = []
for i in range(n):
	l.append(input())
ans = 0
dp = [[0, 0] for i in range(n)]
dp[n - 1][0] = 0
dp[n - 1][1] = m + 1
for i in range(n - 1, 0, -1):
	x = l[i][::-1]
	if '1' in l[i]:
		a = x.index('1')
		b = l[i].index('1')
	else:
		a = m + 1
		b = m + 1
	dp[i - 1][0] = min(dp[i][0] + 2 * (m + 1 - a) + 1, dp[i][1] + m + 2)
	dp[i - 1][1] = min(dp[i][1] + 2 * (m - b + 1) + 1, dp[i][0] + m + 2)
for i in range(n):
	if '1' in l[i]:
		a = l[i][::-1].index('1')
		b = l[i].index('1')
		ans = min(dp[i][0] + m + 1 - a, dp[i][1] + m + 1 - b)
		break
print(ans)


(n, m) = map(int, input().strip().split())
a = []
L = []
R = []
t = {}
for i in range(n):
	b = input()
	a.append(b)
	L.append(9000000)
	R.append(0)
	t[i] = 0
a.reverse()
for i in range(n):
	for j in range(m + 2):
		if a[i][j] == '1':
			L[i] = min(L[i], j)
			R[i] = max(R[i], j)
			t[i] = 1
L1 = 0
R1 = 9000000
ans = 0
for i in range(n):
	if t[i] == 0:
		L1 += 1
		R1 += 1
		continue
	ans = min(L1 + R[i], R1 + m + 1 - L[i])
	L2 = min(L1 + R[i] * 2 + 1, R1 + m + 2)
	R2 = min(R1 + (m + 1 - L[i]) * 2 + 1, m + 2 + L1)
	L1 = L2
	R1 = R2
print(ans)


(n, m) = map(int, input().split())
temp = []
for i in range(n):
	s = input()
	s = s[1:-1]
	temp.append(s)
temp = temp[::-1]
i = len(temp) - 1
while len(temp):
	s = temp[i]
	if s.count('1') == 0:
		temp.pop()
		i -= 1
	else:
		break
n = len(temp)
if n == 0:
	print(0)
	exit()
if n == 1:
	save = 0
	x = temp[0]
	ans = []
	for i in range(len(x)):
		if x[i] == '1':
			save = i
	print(save + 1)
	exit()
dp = [[0 for i in range(n)] for i in range(2)]
dp[0][0] = 0
dp[1][0] = m + 2
for i in range(n - 1):
	s = temp[i]
	ans = []
	for j in range(len(s)):
		if s[j] == '1':
			ans.append(j)
	if i == 0:
		if len(ans):
			dp[0][0] = 2 * (ans[-1] + 1) + 1
		else:
			dp[0][0] = 1
	elif len(ans):
		dp[0][i] = min(dp[0][i - 1] + 2 * (ans[-1] + 1), dp[1][i - 1] + m + 1) + 1
		dp[1][i] = min(dp[1][i - 1] + 2 * (m - ans[0]), dp[0][i - 1] + m + 1) + 1
	else:
		dp[0][i] = dp[0][i - 1] + 1
		dp[1][i] = dp[1][i - 1] + 1
s = temp[-1]
ans = []
for i in range(len(s)):
	if s[i] == '1':
		ans.append(i)
if len(ans):
	dp[0][-1] = dp[0][-2] + ans[-1] + 1
	dp[1][-1] = dp[1][-2] + m - ans[0]
else:
	dp[0][-1] = dp[0][-2]
	dp[1][-1] = dp[1][-2]
print(min(dp[0][-1], dp[1][-1]))


import itertools
(n, m) = list(map(int, input().split()))
floors = []
max_lit = -1
for floor_n in range(n - 1, -1, -1):
	cur_floor = input()
	floors.insert(0, cur_floor)
	if max_lit == -1 and any((c == '1' for c in cur_floor)):
		max_lit = floor_n + 1
if max_lit == -1:
	print('0')
	return

def calc_path(path):
	left = True
	result = 0
	for floor in range(max_lit):
		switch_stairs = path[floor]
		if left:
			pos = floors[floor].rfind('1')
			dist = 0 if pos == -1 else pos
		else:
			pos = floors[floor].find('1')
			dist = 0 if pos == -1 else m + 1 - pos
		is_last = floor == max_lit - 1
		result += dist
		if switch_stairs:
			if not is_last:
				result += m + 1 - dist
			left = not left
		elif not is_last:
			result += dist
		if not is_last:
			result += 1
	return result
min_v = -1
for p in itertools.product([False, True], repeat=max_lit):
	v = calc_path(p)
	if min_v == -1 or min_v > v:
		min_v = v
print(min_v)


(n, m) = map(int, input().split())
a = [input() for i in range(n)]
i = 0
while i < n and a[i] == '0' * (m + 2):
	i += 1
a = a[i:]
n = len(a)
dp = [[10 ** 5, 10 ** 5] for i in range(n)]
for i in range(n):
	(l, r) = (a[i].find('1'), a[i].rfind('1'))
	if l == r == -1:
		(l, r) = (m + 1, 0)
	if i == 0:
		dp[0] = [r, m + 1 - l]
	else:
		dp[i][0] = min(dp[i - 1][0] + 2 * r, dp[i - 1][1] + (m + 1)) + 1
		dp[i][1] = min(dp[i - 1][0] + m + 1, dp[i - 1][1] + 2 * (m + 1 - l)) + 1
ans = dp[-1][0] if dp else 0
print(ans)


def sol():
	(n, m) = map(int, input().split(' '))
	mapp = []
	for a in range(n):
		s = list(input())
		s = [c == '1' for c in s]
		mapp.insert(0, s[1:-1])
	res = None
	empty_floor = n
	while True:
		litup = False
		for x in mapp[empty_floor - 1]:
			if x:
				litup = True
				break
		if not litup:
			empty_floor -= 1
		else:
			break
		if empty_floor < 0:
			break
	if empty_floor <= 0:
		return 0
	for comb in range(2 ** (empty_floor - 1)):
		temp = 0
		c = bin(comb)[2:]
		c = '0' * (empty_floor - 1 - len(c)) + c
		c = list(c)
		c = [x == '1' for x in c]
		last = False
		if empty_floor != 1:
			for (i, x) in enumerate(c):
				if x != last:
					temp += m + 1 + 1
				else:
					f = None
					for (j, y) in enumerate(mapp[i]):
						if y:
							f = j
							if last:
								break
					if f is None:
						temp += 1
					elif last:
						temp += 2 * (m - f) + 1
					else:
						temp += 2 * (f + 1) + 1
				last = x
		f = None
		for (j, y) in enumerate(mapp[empty_floor - 1]):
			if y:
				f = j
				if last:
					break
		if f is not None:
			if c[-1]:
				temp += m - f
			else:
				temp += f + 1
		if res is None:
			res = temp
		res = min(res, temp)
	return res
print(sol())


for _ in range(1):
	(n, m) = map(int, input().split())
	arr = []
	for i in range(n):
		st = input()
		arr.append(st)
	arr = arr[::-1]
	dp = [[m + 1, m + 1] for i in range(n)]
	for i in range(n):
		last = 0
		for j in range(1, m + 1):
			if arr[i][j] == '1':
				last = j
		dp[i][0] = last
		last = 0
		count = 1
		for j in range(m, 0, -1):
			if arr[i][j] == '1':
				last = count
			count += 1
		dp[i][1] = last
	dp_final = [[0, 0] for i in range(n)]
	dp_final[0][1] = m + 1
	mini = dp[0][0]
	for i in range(1, n):
		dp_final[i][0] = min(dp_final[i - 1][0] + 2 * dp[i - 1][0] + 1, dp_final[i - 1][1] + m + 2)
		dp_final[i][1] = min(dp_final[i - 1][1] + 2 * dp[i - 1][1] + 1, dp_final[i - 1][0] + m + 2)
		if arr[i].count('1') > 0:
			mini = min(dp_final[i][0] + dp[i][0], dp_final[i][1] + dp[i][1])
	if mini == 9999999999:
		print(0)
	else:
		print(mini)


import sys
inf = float('inf')
ans = inf

def solve():
	global ans
	(n, m) = map(int, input().split())
	room = [[int(i) for i in input()] for j in range(n)]
	room.reverse()
	exits = [False] * n
	for i in range(n - 1, -1, -1):
		if any(room[i]):
			exits[i] = True
		if i - 1 >= 0:
			exits[i - 1] |= exits[i]
	if not exits[0]:
		ans = 0
	else:
		dfs(0, n, m, room, exits, 0, 0)
	print(ans)

def dfs(floor, n, m, room, exits, pos, move):
	global ans
	k = -1
	if pos == 0:
		for j in range(m + 1, -1, -1):
			if room[floor][j]:
				k = j
				break
		else:
			k = 0
	else:
		for j in range(0, m + 2):
			if room[floor][j]:
				k = j
				break
		else:
			k = m + 1
	move += abs(k - pos)
	if floor == n - 1 or not exits[floor + 1]:
		ans = min(ans, move)
		return
	else:
		dfs(floor + 1, n, m, room, exits, 0, move + k + 1)
		dfs(floor + 1, n, m, room, exits, m + 1, move + m + 1 - k + 1)
solve()


(n, m) = map(int, input().split())
p = 1
l = [[1, 0]]
l1 = []
r = 0
M = [input() for i in range(n)]
for i in range(n):
	if M[i].count('1') == 0:
		r = r + 1
	else:
		break
for i in range(n - 1, r, -1):
	for j in range(len(l)):
		k = l[j][1]
		if l[j][0] == 1:
			l1.append([2, k + m + 2])
			if M[i].count('1') == 0:
				l1.append([1, k + 1])
			else:
				l1.append([1, k + M[i].rindex('1') * 2 + 1])
		else:
			l1.append([1, k + m + 2])
			if M[i].count('1') == 0:
				l1.append([2, k + 1])
			else:
				l1.append([2, k + abs(M[i].index('1') - m - 1) * 2 + 1])
	l = l1
	l1 = []
min = 1000000000
if r == n:
	print(0)
	exit()
for j in range(len(l)):
	if l[j][0] == 1:
		if l[j][1] + M[r].rindex('1') <= min:
			min = l[j][1] + M[r].rindex('1')
	elif l[j][1] + abs(M[r].index('1') - m - 1) <= min:
		min = l[j][1] + abs(M[r].index('1') - m - 1)
print(min)


(n, m) = map(int, input().split())
h = []
l = []
r = []
last = -1
for i in range(n):
	s = input()
	h.append(s)
i = 0
for s in reversed(h):
	(lp, rp) = (m + 1, 0)
	for j in range(len(s)):
		let = s[j]
		if let == '1' and lp == m + 1:
			lp = j
		if let == '1':
			rp = j
	l.append(lp)
	r.append(rp)
	if r[i] != 0 or l[i] != m + 1:
		last = i
	i += 1
dp = [[2 * r[0], m + 1]]
for i in range(1, last):
	prev = dp[-1]
	ml = min(prev[0] + 2 * r[i], prev[1] + m + 1) + 1
	rl = min(prev[1] + 2 * (m + 1 - l[i]), prev[0] + m + 1) + 1
	dp.append([ml, rl])
if last == 0:
	ans = r[0]
elif last == -1:
	ans = 0
else:
	ans = min(dp[-1][0] + r[last] + 1, dp[-1][1] + (m + 1 - l[last]) + 1)
print(ans)


ii = lambda : int(input())
kk = lambda : map(int, input().split())
ll = lambda : list(kk())
(n, m) = kk()
(ls, rs) = ([], [])
emptyTop = 0
topcount = 1
for i in range(n):
	l = r = 0
	for (j, v) in enumerate(input()):
		v = int(v)
		if v:
			r = j
			if not l:
				l = m + 1 - j
	if topcount:
		if l == r == 0:
			emptyTop += 1
		else:
			topcount = 0
	ls.append(l)
	rs.append(r)
ls.reverse()
rs.reverse()
n -= emptyTop
lefts = [0] * (n + 1)
rights = [0] * (n + 1)
rights[-1] = m + 1
i = 0
for i in range(n):
	mult = 2 if i < n - 1 else 1
	lefts[i] = min(lefts[i - 1] + mult * rs[i], rights[i - 1] + m + 1)
	rights[i] = min(rights[i - 1] + mult * ls[i], lefts[i - 1] + m + 1)
print(max(min(lefts[i], rights[i]) + n - 1, 0))


(n, m) = map(int, input().split())
g = [list(input()) for i in range(n)]
max_n = -1
for i in range(n):
	if g[i].count('1') == 0:
		max_n = i
	else:
		break
g = g[max_n + 1:]
n -= max_n + 1
if len(g) == 0:
	print(0)
	exit()
l = [m + 1] * n
r = [0] * n
dp = [[0] * 2 for i in range(n)]
for i in range(n):
	for j in range(m + 2):
		if g[n - 1 - i][j] == '1':
			l[i] = min(l[i], j)
			r[i] = max(r[i], j)
dp[0][0] = r[0] * 2 + 1
dp[0][1] = m + 2
for i in range(1, n - 1):
	dp[i][0] = min(dp[i - 1][0] + r[i] * 2 + 1, dp[i - 1][1] + (m + 1) + 1)
	dp[i][1] = min(dp[i - 1][0] + (m + 1) + 1, dp[i - 1][1] + (m - l[i] + 1) * 2 + 1)
if n == 1:
	print(r[0])
else:
	ans = min(dp[n - 2][0] + r[n - 1], dp[n - 2][1] + m - l[n - 1] + 1)
	print(ans)


import sys

def main():
	(n, m) = map(int, sys.stdin.readline().split())
	m += 2
	z = []
	for i in range(n):
		z.append(sys.stdin.readline().rstrip())
	ans = 0
	y = n - 1
	x = 0
	q = [[x, y, ans]]
	for i in range(n - 1, -1, -1):
		first = -1
		last = -1
		for j in range(m):
			if z[i][j] == '1':
				if first == -1:
					first = j
				last = j
		if first == -1 and last == -1:
			continue
		if i == n - 1:
			q[0] = [last, n - 1, last]
			continue
		if first == last:
			for t in q:
				t[2] += min(t[0] + first, m - 1 - t[0] + m - 1 - first) + t[1] - i
				t[0] = first
				t[1] = i
			continue
		size = len(q)
		for s in range(size):
			t = q[s]
			q.append([last, i, t[2] + t[0] + last + t[1] - i])
			t[2] += m - 1 - t[0] + m - 1 - first + t[1] - i
			t[0] = first
			t[1] = i
			q[s] = t
	ans = q[0][2]
	for i in range(len(q)):
		if q[i][2] < ans:
			ans = q[i][2]
	print(ans)
main()


import collections

def minimum(a, b):
	if a < b:
		return a
	else:
		return b

def find_left(a, m):
	pos = 0
	for i in range(m, -1, -1):
		if a[i] == '1':
			pos = i
			break
	return pos

def find_right(a, m):
	pos = m + 1
	for i in range(1, m + 1):
		if a[i] == '1':
			pos = i
			break
	return pos
(n, m) = input().split()
n = int(n)
m = int(m)
b = []
for i in range(0, n):
	b.append(list(input()))
a = []
for i in range(n - 1, -1, -1):
	a.append(b[i])
dp = []
for i in range(0, n):
	dp.append([0, 0])
j = n - 1
flag = 0
while len(a) > 0 and flag == 0:
	for i in range(0, m + 2):
		if a[j][i] == '1':
			flag = 1
			break
	if flag == 0:
		a.pop()
		n = n - 1
	j = j - 1
if len(a) == 0:
	print(0)
elif len(a) == 1:
	print(find_left(a[0], m))
else:
	dp[1][0] = 2 * find_left(a[0], m) + find_left(a[1], m) + 1
	dp[1][1] = m + 1 + m + 1 - find_right(a[1], m) + 1
	for i in range(2, n):
		dp[i][0] = 1 + minimum(dp[i - 1][0] + find_left(a[i - 1], m) + find_left(a[i], m), dp[i - 1][1] + find_right(a[i - 1], m) + find_left(a[i], m))
		dp[i][1] = 1 + minimum(dp[i - 1][1] + m + 1 - find_right(a[i - 1], m) + m + 1 - find_right(a[i], m), dp[i - 1][0] + m + 1 - find_left(a[i - 1], m) + m + 1 - find_right(a[i], m))
	if dp[n - 1][0] < dp[n - 1][1]:
		print(dp[n - 1][0])
	else:
		print(dp[n - 1][1])


import math as mt
import sys, string, bisect
input = sys.stdin.readline
import random
from collections import deque, defaultdict
L = lambda : list(map(int, input().split()))
Ls = lambda : list(input().split())
M = lambda : map(int, input().split())
I = lambda : int(input())

def leftmost(a):
	for i in range(len(a)):
		if a[i] == 1:
			return m - i + 1
	return len(a)

def rightmost(a):
	for i in range(len(a) - 1, -1, -1):
		if a[i] == 1:
			return i
	return len(a)
(n, m) = M()
l = []
f = 0
for i in range(n):
	x = input().strip()
	y = []
	for j in x:
		y.append(int(j))
	if sum(y) > 0:
		f = 1
	if f == 1:
		l.append(y)
if len(l) == 0:
	print(0)
else:
	l = l[-1::-1]
	ans = [('L', 0)]
	for i in range(len(l) - 1):
		j = len(ans)
		while j > 0:
			if ans[0][0] == 'L':
				if rightmost(l[i]) == m + 2:
					ans.append(('L', ans[0][1] + 1))
					ans.append(('R', ans[0][1] + m + 2))
				else:
					ans.append(('R', ans[0][1] + m + 2))
					ans.append(('L', ans[0][1] + 2 * rightmost(l[i]) + 1))
				ans = ans[1:]
			else:
				if leftmost(l[i]) == m + 2:
					ans.append(('R', ans[0][1] + 1))
					ans.append(('L', ans[0][1] + m + 2))
				else:
					ans.append(('L', ans[0][1] + m + 2))
					ans.append(('R', ans[0][1] + 2 * leftmost(l[i]) + 1))
				ans = ans[1:]
			j -= 1
	w = 10 ** 20
	for i in range(len(ans)):
		if ans[i][0] == 'L':
			if rightmost(l[-1]) == m + 2:
				w = min(w, ans[i][1])
			else:
				w = min(w, ans[i][1] + rightmost(l[-1]))
		elif leftmost(l[-1]) == m + 2:
			w = min(w, ans[i][1])
		else:
			w = min(w, ans[i][1] + leftmost(l[-1]))
	print(w)


import math
(n, m) = (0, 0)
right_distance = []
left_distance = []

def calculate_left_distance(floor_structure):
	global left_distance
	for i in range(n):
		for j in range(m, 0, -1):
			if floor_structure[i][j] == '1':
				left_distance.append(j)
				break
		else:
			left_distance.append(0)

def calculate_right_distance(floor_structure):
	global right_distance
	for i in range(n):
		for j in range(1, m + 1):
			if floor_structure[i][j] == '1':
				right_distance.append(m + 1 - j)
				break
		else:
			right_distance.append(0)

def calculate_time(floor_structure, pos, index):
	if index == 0:
		if pos == 'l':
			return left_distance[index]
		return right_distance[index]
	if pos == 'l':
		left = calculate_time(floor_structure, 'l', index - 1)
		right = calculate_time(floor_structure, 'r', index - 1)
		if left == 0:
			return left_distance[index]
		return min(left + 2 * left_distance[index] + 1, right + m + 2)
	else:
		left = calculate_time(floor_structure, 'r', index - 1)
		right = calculate_time(floor_structure, 'l', index - 1)
		if left == 0:
			return right_distance[index]
		return min(left + 2 * right_distance[index] + 1, right + m + 2)

def main():
	global n, m
	(n, m) = [int(x) for x in input().split()]
	floor_structure = []
	for i in range(n):
		temp = input()
		floor_structure.append(temp)
	calculate_left_distance(floor_structure)
	calculate_right_distance(floor_structure)
	print(calculate_time(floor_structure, 'l', n - 1))
main()


R = lambda : map(int, input().split())
(n, m) = R()
l = []
top = -1
for i in range(n):
	l1 = input()
	l.insert(0, l1)
	if top is -1 and l[0].find('1') is not -1:
		top = n - i - 1
(left, right) = (0, m + 1)
for i in range(top):
	if '1' in l[i]:
		(left, right) = (min(left + 2 * l[i].rfind('1') + 1, right + m + 2), min(left + m + 2, right + 2 * (m + 1 - l[i].find('1')) + 1))
	else:
		(left, right) = (left + 1, right + 1)
print(max(0, min(left + l[top].rfind('1'), right + (m + 1 - l[top].find('1')))))


INT_INF = 1061109567

def solve():
	left = [0 for _ in range(n + 5)]
	right = left.copy()
	for i in range(st, n + 1):
		(mi, ma) = (m + 2, 1)
		for j in range(1, m + 3):
			if s[i][j] == '1':
				mi = min(mi, j)
				ma = max(ma, j)
		left[i] = mi
		right[i] = ma
	dp = [[INT_INF, INT_INF] for _ in range(n + 5)]
	dp[n + 1][0] = -1
	for i in range(n, st, -1):
		dp[i][0] = min(dp[i + 1][0] + (right[i] - 1) * 2, dp[i + 1][1] + m + 1) + 1
		dp[i][1] = min(dp[i + 1][0] + m + 1, dp[i + 1][1] + (m + 2 - left[i]) * 2) + 1
	ans = min(dp[st + 1][0] + right[st] - 1, dp[st + 1][1] + m + 2 - left[st]) + 1
	return ans

def judge():
	for i in range(1, n + 1):
		for ch in s[i]:
			if ch == '1':
				return False
	return True
while True:
	try:
		(n, m) = map(int, input().split(' '))
		s = [0] + ['0' + input() for _ in range(n)]
		if judge():
			print('0')
			continue
		st = 1
		for i in range(1, n + 1):
			flag = True
			for j in range(1, m + 3):
				if s[i][j] == '1':
					flag = False
					break
			if flag:
				st += 1
			else:
				break
		print(solve())
	except:
		break


(n, m) = map(int, input().split())
a = [list(map(int, input())) for i in range(n)]
a.reverse()
dp = [[0, 0] for i in range(n + 2)]
dp[0][1] = 10000
last_none = -1
last = -1
for i in range(1, n + 1):
	(f, l) = (-1, -1)
	for j in range(1, m + 1):
		if a[i - 1][j] == 1:
			if f == -1:
				f = j
			l = j
	if f == -1:
		if last_none == -1:
			last_none = i
		if last + 1 == i:
			last_none = i
		dp[i][0] = dp[i - 1][0] + 1
		dp[i][1] = dp[i - 1][1] + 1
		continue
	else:
		last = i
	dp[i][0] = min(dp[i - 1][0] + 2 * l, dp[i - 1][1] + m + 1) + 1
	dp[i][1] = min(dp[i - 1][1] + 2 * (m + 1 - f), dp[i - 1][0] + m + 1) + 1
t = last
(f, l) = (-1, -1)
if t != -1:
	for j in range(1, m + 1):
		if a[t - 1][j] == 1:
			if f == -1:
				f = j
			l = j
	ans = min(dp[t - 1][0] + l, dp[t - 1][1] + (m + 1 - f))
else:
	ans = 0
print(ans)