// No sorcery shall prevail. //
import java.util.*;
import java.io.*;
public class InVoker {
	//Variables
	static long mod = 1000000007;
	static long mod2 = 998244353;
	static FastReader inp= new FastReader();
	static PrintWriter out= new PrintWriter(System.out);
	public static void main(String args[]) {
	   	InVoker g=new InVoker();
	   	g.main();
	   	out.close();
	}

	//Main
	void main() {

		int t=inp.nextInt();
		while(t-->0) {
			long x=inp.nextLong();
			long y=inp.nextLong();
			long c[]=new long[7];
			for(int i=1;i<=6;i++) c[i]=inp.nextLong();
			long gg;
			if(x>=0 && y>=0) {
				if(y>=x) {
					gg=Math.min(c[1]*y+c[3]*(y-x), Math.min(c[2]*y+c[6]*x,c[1]*x+c[2]*(y-x)));
				}else { // x>y
					gg=Math.min(c[1]*x+c[5]*(x-y), Math.min(c[6]*x+c[2]*y, c[1]*y+c[6]*(x-y)));
				}
			}else if(x>=0) {
				gg=Math.min(c[1]*x+c[5]*(x-y), Math.min(c[5]*(0-y)+c[6]*x,c[4]*(0-y)+c[6]*(x-y)));
			}else if(y>=0) {
				gg=Math.min(c[1]*y+c[3]*(y-x), Math.min(c[3]*(0-x)+c[2]*y,c[4]*(0-x)+c[2]*(y-x)));
			}else {
				if(x<=y) {
					gg=Math.min(c[4]*(0-y)+c[3]*(y-x), Math.min(c[3]*(0-x)+c[2]*(y-x),c[4]*(0-x)+c[2]*(y-x)));
				}else { // x>y
					gg=Math.min(c[4]*(0-x)+c[5]*(x-y), Math.min(c[5]*(0-y)+c[6]*(x-y),c[4]*(0-y)+c[6]*(x-y)));
				}
			}
			out.println(gg);
		}

	}

	/*********************************************************************************************************************************************************************************************************
	 * ti;.                               .:,:i:         :,;;itt;.        fDDEDDEEEEEEKEEEEEKEEEEEEEEEEEEEEEEE###WKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWW#WWWWWKKKKKEE      :,:.    f::::. .,ijLGDDDDDDDEEEEEEE*
	 *ti;.                               .:,:i:          .:,;itt;:      GLDEEGEEEEEEEEEEEEEEEEEEDEEEEEEEEEEE#W#WEKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKKKKKKG.     .::.      f:,...,ijLGDDDDDDDDEEEEEE *
	 *ti;.                               .:,:i:            :,;;iti,    :fDDEEEEEEEEEEEEEEEKEEEEDEEEEEEEEEEEW##WEEEKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWWKKKKKKEG     .::.       .f,::,ijLGDDDDDDDDEEEEEE *
	 *ti;.                               .:,:i:             .,,;iti;.  LDDEEEEEEEEEEKEEEEWEEEDDEEEEEEEEEEE#WWWEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWWWWWKKKKKEDj    .::.        .:L;;ijfGDDDDDDDDDEEEEE *
	 *ti;.                               .:,:i:              .:,;;iii:LLDEEEEEEEEEEEKEEEEEEEEDEEEEEEEEEEEW#WWEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKWWKWWWWWWWWWWWWWWKKKKKKKEL    .::.         .:;LijLGGDDDDDDDDEEEEE *
	 *ti;.                               .:,:;:                :,;;ittfDEEEEEEEEEEEEEEEEKEEEGEEEEEEEEEEEKWWWEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWWWWKKKKKKKELj   .::.          :,;jffGGDDDDDDDDDEEEE *
	 *ti;.                               .:,:i:                 .,;;tGGDEEEEEEEEEEEKEEEKEEEDEEEEEEEEEEEEWWWEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWKWWWWWWKKKKKKKEEL   .::.          .:;itDGGDDDDDDDDDEEEE *
	 *ti;.                               .:::;:                   :;ifDEEEEEEEEEEEEKEEEKEEEEEEEEEEEEEEEWWWEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WWWKKKKKKKKEEf   .::.           :,itfGEDDDDDDDDDDDEE *
	 *ti;.                               .:::;:                    :GGEEEEEEEEEEEKEKEEKEEEEEEEEEEEEEEEEWWEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKKEEDG  .::.           .,;jfLGKDLDDDDDDEEDD *
	 *ti;.                               .:::;:                     fDEEEEEEKKKKKKKKKEKEEEEEEEEEEEEEEE#WEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#KKKKKKKKKKEEf .:::.           .,;tfLGDEDDDDDDDDEEE *
	 *ti;.                                :::;:                    fDEEEEEEKKKKKKKKKKWKEEEEEEEEEEEEEEEWKEEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKKKEEft :::.           .,;tfLGDDDKDDDDDDDDD *
	 *ti;.                                .::;:                    fDEEEEEEKKKKKKKWKKKKKEEEEEEEEEEEEE#WEEWEEEEEDEEDEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKKKEEGG :,:.           .,;tfLGGDDDKDDDDDDDD *
	 *ti;.                                .:.;:                   tGDEEEEKKKKKKKKKKKKKKKKKEEEEEEEEEEEWEEKWEEEEEEEDEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKKKKKEEDf :::.           .,;tfLGGDDDDEDDDDDDD *
	 *ti;.                                .::;:                   fDEEEEEKKKKKKKKKKKWKKKKKKKKEEEEEEEWWEEWEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKW##KKKKKKKEEEft.::.           .,;tfLGGDDDDDDEDDDDD *
	 *ti;.                                .:.;:                  tGDEEEKKKKKKKKKKKKKKKKKKKKKKEKEEEEE#EEWWEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKW#WKKKKKKEEEGD:::.           .,;tfLGGDDDDDDDEDDDD *
	 *ti;.                                .:.,.                  LDEEEEKKKKKKKKKKWKWKKKKKKKKKKKKEEEKWEKW#EEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKW##KKKKKKEEEEf,,:.           .,;tfLGGDDDDDDDDEDDD *
	 *ti;.                               ..:.,.                 LGDEEEEKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEEW#WEEEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEKEKKKKKKKKKKKKKKKK##KKKKKEEEEEfi;,.           .,;tfLGGDDDDDDDDDKDD *
	 *tt;.                                .:.,:                 jDEEEEKKKKKKKKKKWWKKKKKKKKKKKKKKKKKWKE#WWEEEEEEEEEEEEEEWEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKKKKKKWWKKKKEEEEDfG;,:           .,;tfLGGDDDDDDDDDDKD *
	 *tii,.                               .:.,.                tGDEEEEKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKKWWWKEEEEEEEEEEEEEKEEEEEEEEEEEEEEEEEEEEEEEEEEEEEKKKKKKKKKKKW#KKKKEEEEDGGi;,.          .,;tfLGGDDDDDDDDDDDE *
	 *ti;;,:.                             .:.,:                fDEEEEKKKKKKKKKKKWKKKKKKKKKKKKKKKKKWEK#WWKEEEEEEEEEEEEDEEEEEEEEEEEEEEGEEEEEEEEEEEEEEEEEEEKKKKKKKWWKKEEEEEEDDf;;;,.         .,;tfLGGDDDDDDDDDDDD *
	 *tii;,,:..                           ...,.               ;LEEEEEKKKKKKWKKKKWKKKKKKKKKKKKKKKKKEKKW#WEEEEEEEEEEEEEjEEEEEEEEEKEEEEGEEEEEEEEEKEEEEEEEEEEEEEEEEE#WKEEEEEEDDf;;;;,:        .,itfLGGDDDDDDDDDDDD *
	 *ti;,,,,,:.                          ...,.               LDEEEEKKKKKKKKKKKWWWKKKKKKKKKKKKKKKWKK#W#WEEEEEEEEEEEDDLEEEEEEEEEWEEEEDEEEEEEEEEKEEEEEEEEEEEEEEEEEWWEEEEEEEDDfj,,,,,:.      .,itfGGGDDDDDDDDDDDD *
	 *tii,,,,::::.                        ...,:              .fDEEEEKKKKKKWKKKKWWWKKKKKKKKKKKKKKKEKKW#WWEEEEEEEEEEEKiKEEKEEEEEEWEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEEWWEEEEEEEDDLD:::,,,:.     .,ijfGGGDDDDDDDDDDDD *
	 *ti;:::::::::..                      .:.,:              LDEEEEKKKKKKKWKKKKWWKKKKKKKKKKKKKKKKtKKWWWWKEEEEEEEEEDiiDEEEEEEEEWWEEEEEEDEEEEEEEEEEEEEEEEEEEEEEEEEEWKEEEEEDDDGL:. .:,,,:    .,ijLGGGDDDDDDDDDDDD *
	 *tt;. .::::::::..                    ...,:             :fDEEEKKKKKKKKKKKKWW#KKKKKKKKKKKKKKKKfKKWWWWKEEEEEEEEDti,DEKEEEEEEWWEEEDEEEEEEEEEKEEEEEEEEEEEEEDEEEEE#WEEEEEGGDGf:.  .:,;,:.  .,ijLGGDDDDDDDDDDDDD *
	 *tt;.   .:::::::..                   ...,:             GDEEEKKKKKKKKWKKKKWWWKKKWKKKKKKKWWWKDEKLWWWWKKEEEEEEDEi,LDEEEEEEEEWWEEEEEEEEEEEEEEEEEEEEEEEEEDEDEEEEEW#EEEEDDDDGf,.    :,,,:...,ijLGGGDDDDDDDDDDDD *
	 *tt;.    .....::::..                 ...,:             fDEEEKKKKKKKKWKKKKWWWWKKKWKKKKKKKKKKfWKiWWW#KKEEEEEEEi;.EDfEEEDEEiWWEEEEEEEEEEEEDGKEEEEEEEEEEDEEEEEEEWWEEEEDDDGGLi.     .,;,:::,ijLGGGDDDDDDDDDDDD *
	 *tt;.      ....:::::.                ...,.            iDEEEEKKKKKKKKWKKWKWWWWWKKWWWKKKKKKKKtWKt#WWWKKEEEEEDji..DDKDDEDEGiWKEEEEEEEEEEDDEjEEEEEEEEEEEDEEEEEEEKWKEEDDDDGGff.      .:,;,,;ijLGGGDDDDDDDDDDDD *
	 *tt;.        ....::::..              .:.,:           .LDEEEKKKKKKKKKKKKWWWWKWWWWWWWWWWKKKKWtKKiDWWWKKKEEEEKi:..DEDDDDDDiiWKEEEEEEEEEEDDEijDEEEEEKEEEEEEEEEEEEWWEEGDDDGGLG.       .:,;;iijLGGGDDDDDDDDDDDD *
	 *tt;.          .....:::..            ...,.           .fEEEEKKKKKKKKWKKKKWWWWWWWWWWWWWWKWKKKiKDiLWWWWKEEEEEi,..fD:DDDDDti;WEEEEEEEEEEKDDi:iDDEEEEWEEEEEEEEEEEE#WEEGDDDDGGG.         :,iitjLGGGDDDDDDDDDDDD *
	 *tti.            .....:::..          ...,.           GDEEEKKKKKKKKKWKKKWWW#WWWWWWWWWWWKWKKjiEjitWWWKKWEEEDi...DDLDDDDji;;WEEEEEEEEEEEDEj.iDDEEEEWEEEEEEEEEEEEWWEEDDDDDDGf.          .,;tjfLGGDDDDDDDDDDDD *
	 *tti.              ....::::..        ...,.           fEEEKKKKKKKKKKKKKKKW#WWWWWWWWWWWWWWWWtiEiiiWWWKKEWKEi....D.EDDDEi;.fWEEEEEEEEEEDDfL.;EDDEEEWEEEEEEEEEEEEWWEEEDDDDDGf.           :;ijfLGGDDDDDDDDDDDD *
	 *tti.                ....::::..      ...,.          LDEEEKKKKKKKKKKKKKKWWWWWWWWWWWWWWWW####WKiiiWWWKKKEEK,...:E:DDDEii..GWEEEEEEEEDWDDiL.,KDDEEEWEEEEEEEEEEEEWWKEEDDDDDGf:           .,itfLGGDDDDDDDDDDDD *
	 *tti.                 .....:::..     ...,.          fDEEEKKKKKKKKKWKKKKWWWWWWWWWWWWW########WLiiWWWKKKEEjD...G,DDDDi;...EWEEEEEEEEDKDEii..LDDEEEWEEEEEEEEEEEEWWWEEDDDDDGfi           .,;tfLGGGDDDDDDDDDDD *
	 *tti.                   .....:::..   ...,.         iGEEEKKKKKKKKKKWKKKKWWWWWWWWWWWW###########KiWWWKKEEE,.D..D.DDDii:...KKEEEEEEEEEDDj:...tEDEEEWEEEEEEEEEEEEWWWEEEDDDDDLL           .,;tjLLGGDDDDDDDDDDD *
	 *tti.                     ....::::......:.         LEEEKKKKKKKKKKWWKKKWWW#KWWWWWWWW#####W####W##KWWKKEEL..:D.jjDDi;,....KKEEEEEEEDfDDi...:iKDEEEWKEEEEEEEEEEEWWWEEEEDDDDLG           .,;tjLLGGDDDDDDDDDDD *
	 *tti.                        ...::::::..,.        :GEEEKKKKKKKKKKKKWWWWW##WWWWWWWWW##WKWK#W#W####WWKEEK.....G.DDti,.....KKEEEEEEDWGDf.,...iKDEEEWWEEEEEEEEEEEW#WEEEEEDDDGL           .,;tjLLGGDDDDDDDDDDD *
	 *tti.                         ....::::::,.        GDEEKKKKKKKKKKKKKWWWW###WWWWWWWWWW#WWWK###W#####WKEKK.....jDDL;;......KKEEEEEEEEEDi.f...;KDEEEWWEEEEEEEEEEEWWWWEEEEEDDGf           .,;tjLLGGDDDDDDDDDDD *
	 *tti.                           ....:::,,.       .LEEEKKKKKWKKKKKWWWWWW###WWWWWWWWWW#WWKW#WW##W#WWWKEKD:....:DD:;......;KEEEEEEEKiDD..f...,KKEEEWWEEEEEEEEEEEWWWWEEEEEDDDf           .:;tjLLGGGDDDDDDDDDD *
	 *tti.                             ...::,,,:.     GDEEKKKKKKKKKKKKWWWWWWW#WWWWWWWWWWW#KjKWWWWWWWWWWWWEK.j,..;fD.;.......fKEEEEEDKG:Di..,....DKEEEWWEEEEEEKEKKKWWWWEEEEEEDDf           .:;tjLLGGDDDDDDDDDDD *
	 *jti.                              ...::,,,,:.  .fEEEKKKKKWKKKKKKWWWWWWW#WWWWWWWWWWK#KKKWWWWWWWWWWWWWK..f:.:G.,:.......EKEEEEEKK;:E:.......fKEEEWWKEKEKKKKKKKW#WWEEEEEEDDf:          .,;tfLLGGDDDDDDDDDDD *
	 *tti.                               ...:,,,;;,: iDEEKKKKKWKKKKKKKWWWWWWW#WWWWWWWWWWK#WDKWWKKWWWWWWWWWE..;G:G..,........KKEEEEEKi.Gi..:.....tKEEKWWWKKKKKKKKKKW##WKEEEEEEDfi          .,;tfLLGGGDDDDDDDDDD *
	 *tti.                               ....::,,;;;,LEEKKKKKKWKKKKKWWWWWWW###WWWWWWWWWWKWWDKWEEEWKKWWWWWKKj.:LG..;.........EKEEEEKG;.G...;.....;KKEKWWWKKKKKKKKKKW##WWKEEEEEDfL          .,;tfLGGGDDDDDDDDDDD *
	 *jti.                                ...::::,;ijDEEKKKKKWKKKKKKWKWWWWW##WWWWWWWWWWWKK#KKGDGDWEEWKKWKKGE,.i;.:.........:EKEEEKE;.:L...j.....,KWEKWWWKKKKKKKKKK####WKKEEEEDLG          .,;tfLGGGGDDDDDDDDDD *
	 *jti.                                ...:...,,;GEEKKKKKWWKKKKKWWWWWWWW###WWWWWWWWWKKKWWKiLGGEDEDEKGKKiEG..;...........jKEEEKK;:.G....,.....:KKEWWWWKKKKKKKWKK####WKKKKEEEGL          .,;tfLGGGGDDDDDDDDDD *
	 *jti.                                ...:.  .:,GEEKKKKKWKKKKKWWWWWWWW####WWWWWWWWWKKKWWKii;fDLGDK: EEi:E:.............EKEEKK;;..L...........KKKWWWWKKKKKKKWKK####WKKKWKEEDf          .,;tfGGGGDDDDDDDDDDD *
	 *jti.                                ...:.    ,EEKKKKKWWKKKKKWWWWWWWWW###WWWWWWWWKKKKfWWLt;i,. fi  EG..D:.............EKEKK;;..t....:.......KWKWWWWKKKKKKKWKK####WKKKWEEEDf:.        .,;tfGGGGDDDDDDDDDDD *
	 *jti.                                ...:.    GEEKKKKKWKKKKKWWWWWWWWW####WWWWWWWKKKKKt;KKEfff     .;t.................KKKKi;:..GtGGfG.......KWWWWWWKKKKKKKWKK###WWWKKKKEEEf,,:       .,;tfGGGGDDDDDDDDDDD *
	 *jti.                                ...:.    GEKKKKKWWKKKKKWWWWWWWWWW##WWWWWWWKKKKKKt;EiKKKK,   ...t................jEKKG;;..,.....,LGi....KWWWWWWKKKKKKWKKKW####WKKKKKEEL,,,:.     .,;tfGGGDDDDDDDDDDDD *
	 *jti.                                ...:.  .GEEKKKKKWKKKKKWWWWWWWWWW###WWWWWWWKKKKKKtiE::tGG........................EEEj;;...,.........:D..DKWWWWWWKKKKK#KKW###W#WKKKKKEEfj:,,,:.   .,;tfGGGDDDDDDDDDDDD *
	 *jti.                                ...:.   DEKKKKKWWKKKKKWWWWWWWWW####WWWWWWWKKKKKKiiE:::.::.......................EEi;;...j.....f......:iDKWWWWWWKKKKK#WW######WKKKKKEELG :,,,,:. .,;tfGGGDDDDDDDDDDDD *
	 *jti.                                ...:.  fEEKKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKK;tE::..........................DD;.;,.::......;........EWWWWWWWKKKKW#WW#####WWKKKWKKELG  .:,,,:::,;tfGGGDDDDDDDDDDDD *
	 *jti.                                ...:. .DEKEKKKWWKKKKWWWWWWWWWWW###WWWWWWWWKKKKKE,iD::..........................D..,;.,;tLffi...........DWDWWWW#KKKWWWWW#####W#KKKWKEEGL    .:,;,,,;tfGGGDDDDDDDDDDDD *
	 *jti.                                ...:. ;EEKKKKWWKKKKKWWWWWW#WWWW####WWWWWWKKKKKEL:iD:..........................j ..;..;;:.....i,........DKtWWWWWKKWWWWWW#####WWWKKKEKEDf     .:,;;;itfGGGDDDDDDDDDDDD *
	 *jti.                                ...:. DEKKKKKWWKKKKWWWWWWW#WWWW####WWWWWWKKKKKEj:iG...............................:....................GKiWWWWWKKWW#WWW######WWKKKKKEEf       .,;iitfGGGDDDDDDDDDDDD *
	 *jti.                                ...:.:EKKKKKWWKKKKKWWWWWWW#WWW#####WWWWWKWKKKKEi:if:.................................iEKEKKKKKKDj......DKiWWWWWKWK##WW#######WWKKK:KEEL        .:;itfGGGDDDDDDDDDDDD *
	 *jji.                                ...:,DEEKKKWWWKWKKWWWWWWWWWWWW#####WWWWWWWKKKKEi:it..................................j.  KKKKKKKKKKKf..DKiWWWWWKWW##WW#######WWKKK,KEEf         .,;tfGGGDDDDDDDDDDDD *
	 *jji.                                ..L:iDEEKKKWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKKi.i;..................................  . KKKWWWWWWWWK..DGiWWWWWKK##WWW#####W#WWKKKjEKEL,        .:;tfGGGDDDDDDDDDDDD *
	 *jji.                               .f:::EEEKKKWWWKKKKKWWWWWWWWWWWW#####WWWWWKWKKKKK;.i,.................................::  KKEKWWWWWWfWK..EiiWWWWWKWW#WW##########KKKD,KELj        .:;tfGGDDDDDDDDDDDDD *
	 *jji.                             .t::::,DEEKKKWWKKKKWWWWWWWWW#WWWW#####WWWWKKWKKKEK;.i:.................................GDDEEEKKKWWWWWtWWD.E;iWWWWWW###WW#########WWKKK.EEDG        .:;tfGGGDDDDDDDDDDDD *
	 *jji.                          . j..::::EKEKKKWWWKKKKWWWWWWWWW#WWW######WWWWKKWKKKEK;.t:.................................ELLEDDEEEWWWWEtWK,.KiiWWWWWW###W##########WWKKK:EEEG     .;tjfLLGDDDDDDDDDDDDDDD *
	 *jji.                          i.::::::,EEEKKWWWKKKKKWWWWWWWWW#WWW#####WWWWWKWKKKKEE,.t..................................DfiEGDDDEEKKKttKWG.KiiWWWWW##WWW##########WWKKK:fEEL  ,fGGGDDDDDDDDEEEDDDDDDDDDD *
	 *jji.                        .;:..:::::DEEEKKWWWKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKED,.t..................................ifjDDGGEGDKK.ttKKE.DiWWWWW###WW##########WWWKKK:.KELiLGGGGDDDDDDDDDDDDEEEDDDDDDD *
	 *jji.                       i.:.::::::,KEEKKWWWKKKKKKWWWWWWWWW#WWWW####WWWWWWWKKKKEL:.j..................................GGf,;ifLLED .iiKKi:fWWWWWW##W#W##########WWWKKK:.KKLGGDDDDDDDDDDDDDDDDEDDEEDDDDD *
	 *jji.                     .j:.::::::::EEEKKKWWWKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKf:.f..................................:EEfftf .,. ;iE,..jWWWWWWW###W############WWKKK,:KKGDDDDDDDDDDDDDDDDDDDDDDDEDDDD *
	 *jji.                    .:.::::::::,,EEEKKWWWKKKKKKKWWWWWWWW##WWW#####WWWWWWWKKKKKt..G....................................EEELL;   .j....tKWWWWWWW################WWWKKtfGKGEDDDDDDDDDDDDDDDDDDDDDDDEEDD *
	 *jji.                   :...:::::::,,jEEKKWWWWKKKKKKWWWWWWWWW##KWW#####KWWWWWWKKKKEi..D....................................:jEEE.........;KKWWWWWWWW#WW##W##########WWKKDLGKEKDDDDDDDDDDDDDDDDDDDDDDDDDED *
	 *jji.                  i:.::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWW##WWW#####WWWWWWWKKKKKi..D......................................:::::......,KKKWWWWWWWWW#####W########WWWKKKGGKKEGGGGGGGGDDDDDDDDDDDDDDDDDDE *
	 *jji.                 i..:::::::::,,tEEKKWWWWKKKKKWWWWWWWWWWW##WW######WWWWWWWKKKKKi..D......................................::::......:EKKKWWWWWWWWWWW##WW########W#WKKWGGKKGGGGGGGGGGGGGGGDDDDDDDDDDDDD *
	 *jji.                .:::::::::::,,,EEEKKWWWWKKKKKWWWWWWWWWWW##WW#####WWWWWWWWKKKKKi..D....................................:::::::::..tELii;KWWWWWWWWWW##WW######WWWWWWKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGDG *
	 *jjt.                :.::::::::,,,,fEEKKWWWWKKKKKKWWWWWWWWWW###WW####WWWWWWW#WKKKKKi..D....................................:::::::.:.,;;;;;;,KKWWWWWWWWW#WW########WWWKKWGGGKGGGGGGGGGGGGGGGGGGGGGGGGGGGG *
	 *jji.               ;.::::::::,,,,;EEEKWWWWWKKKKKWWWWWWWWWWWW##WW###WKWWWWWK#WKKKKKi..G......................................:::::::,;;;;:...KKKWWWWWWWWWKWW#######WWWWKKGLGKDGGGGGGLLGGGGGGGGGGGGGGGGGGG *
	 *jjt.              f.:::::::::,,,,fEEKKWWWWWKKKKKWWWWWWWWWWW###WW##WKKWWWWWW#WKKKKK;.jt........i.............................:::::::;j;;....:E.KKKWWWWWWWKWW#####W#WWWWKKLLGWEEGGGGGLGGGGGGGGGGGGGGGGGGGG *
	 *jjt.             ...:::::::,,,,,;DEEKWWWWWKKKKKWWWWWWWWWWWW####WWWKKKWWWWWWWWKKKKK;.E;.........t.............................:::::ii;;.....D...KKWWWWWWWKWW#####WWEWWWKKGGGEKKGGGGGLGGGGGGGGGGGGGLGGGGGG *
	 *fji.             ;.:::::::,,,,,;LEEKKWWWWWKKKKKWWWWWWWWWWWW####KWKKKKWWWWWWWWKKKKKi.D;..........j.............................:::tt;,.....:.....KKWWWWWWKWWWW##WWWGWWWKKGGGGKEGGGGGGGGGGGGGGGGGGGLLGGGGL *
	 *fji.            t::::::::,,,,,,;EEEKWWWWWKKKKKKKWWWWWWWWWWW##WKWKKKKKWWWWWWWWKKKKKi:D;............j...........................::LL;,.............KKWWWWWKWWWWWWWWWGWWWKKGGGGKGGGGGGGGGGGGGGGGGGGGLLGGGGL *
	 *fjt:            .:::::::,,,,,,,DEEKWWWWWWKKKKKKKWWWWWWWWWWWWKKWKKKKKKWWWWK#WWKKKKWitE;........... ............................:G;;:...............KKKWWKKWWWWWWWWWGWWWKKGGGGWGGGGGGGGGGGGGGGGGGGGGGGGGGL *
	 *fjji;:.       .f:::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWWKKKKKKKKKKKWWKWWWWWKKKKWGKD;........................................L;;..................DKKWKKWWWWWWWWWGWWWKKDGGGKDGGGGGGGGGGGGGGGGGGGGGGGGGG *
	 *fjjtii;,:.     :::::::,,,,,,,;EEEKWWWWWWKKKKKKWWWWWWWWWWKKKKKKKKKKKKWWWWWW#WWKKKKWiEj;......................................:i,;....,...............;KKEKWWWWWWWWWGKWWKKDDGGDEGGGDGGGGGDGGGGGGGGGGGGGGGG *
	 *fjtiiiii;;:.  j::::::,,,,,,,;;EEEKWWWWW#KKKKKWWWWWWWWWKKKKKKWKKKKKKKWWWWWWWWWKKKKWtEL;:....................................;;;:...,;j................:KEEWWWWWWWWWDDWWKKDDDDDKDDDDDDDDDDDDDDDGGGGGGGGGGG *
	 *fjti;;iiii;;,:::::::,,,,,,,,;EEEKWWWWWWWKKKKWWWWWWWWKKKKKKKWKKKKKKKWWWWWWW#W#KKKKWEEii;...................................f;:....,;L...................EEKWWWWWWWWDDWWKKDDDDDKEDDDDDDDDDDDDDDDDDDDDDGGGG *
	 *fjt,,,;;;;ii;f::::::,,,,,,,;;EEKWWWWWWWKKKKKWWWKWWKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWKEij;:...............................:G;,.....,;f....................:tKKWWWWWWWDDWWKKDDDDDKKDDDDDDDDDDDDDDDDDDDDDDDDD *
	 *jjt. ..:,;;;;,::::,,,,,,,,;;GEEWWWWWWWWKKKKWKKWKKKKKKKKKKKKKKKKKKKKWWWWWWW#W#KKKKWEDi;j;............................,Li;L;;;..,;;f........................KKKKWWWKDDWWKKDDDGDKKGGGGGGGGDGDDDDDDDDDDDDDDD *
	 *fjt.    .:,,,:::::,,,,,,,;;;EEKWWWWWWWKKKKKKWKKKKKKKKKKKKKKKKKKKKKWKKKWKW##W#KKKKWEti;;G;........................tEEEL;;;;;;;;;;L..........................DKKKKKEDDWWKEDGftiLE;;;;itjLGGGGGGDDDDDDDDDDD *
	 *fjt.       .j::::,,,,,,,;;;DEEWWWWWWWWKKKKWKKKKKKKKKKKKKKKKKKKKKKKWKKWWWK##W#KKKKKEii;;;L;...................iDEEEEEEKKi;j;;;;jD.....:......................,KKKKDGGEKKE:::::;E::::::::::,tLGGDDDDDDDDDD *
	 *fjt.       .;:::,,,,,,,;;;;EEKWWWWWWWWKWKKKKKKKKKKKKKKKWKKKKKKKKKKWKKWWWW#WW#KKKKKKii;;;;f;.............:tDEEEEEKKKKKKKKEti;;;L...............................EEKf;:iKKE::::::E::::::::::::::ifDDDDDDDDD *
	 *fjt:        :::,,,,,,,,;;;DEEWWWWWWWWWEKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####KKKKKEiii;;;;f,.........iDEEEEKKKKKKKKKKKKKKKf;iG......i..........................fK::::KKE::::::E::::::::::::::::,tGGDDDDD *
	 *fjt:       t:::,,,,,,;;;;iDEKWWWWWWKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKWWWW####WKKKKLiii;;;;;L,....,Li;EDEEEEKKKKKKKKKKKKKKKKiG......;:...........................:i:::KKE:::::,E,::::::::::::::::::iGDDDD *
	 *jjt.       f::,,,,,,,;;;;GEEWWWWKEEKEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKWWWWW###WWKKKKiii;;;;;;;G,;L;;iiEEEEEEEKKKKKKKKKKKKKWWKE......;t.........:....................j::KEE:,::,,D,,::::,,,,,,:::::::::tDDD *
	 *fjt:.      ,::,,,,,,,;;;;EEWWKEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKWWKKWWWWW#W#KKKKKKiiiiii;;;;;i;;iiiEEKEEKKWKKKKKKKWKKKKKWWWGi;...;t......,;;;;,....................:,EEE,,,,,,D,,,,,,,,,,,,,,,,::,::::tG *
	 *fjt:.     ,::,,,,,,,;;;;DEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWW#W#KKKKKKiiiii;;i;;;;;iiiKKKEKKKKWWKWWWWWWKKKKWWWWW;;;:;L.....;;;;;;;;;....................,KEE,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,; *
	 *fjt:.     f:,,,,,,,;;;;jEDEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWW#W##KKKKKKiiiiiiii;i;;iiiEKKKKKKKKWKWWWWWWWWKKKWWWWWKi;;i.....,jEEfGi;;;;;...................EED,,,,,,E,,,,,,,,,,,,,,,,,,,,,,,,, *
	 *fjt:.    .f::,,,,,,;;jEEDEEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWKWWWWW###KKKKKLiiiiiiiiiiiiiiEEKKKKKKKKWWWWWWWWWWWWKWWWWWWGi;i;,..;jDDDKEGi;;;;;;:................EED,,,,,,D,,,,,,,,,,,,,,,,,,,,,,,,, *
	 *fjt:.  .. ;::,,,,,;;EDDEEEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWKKW#WW####KWKKKiiiiiiiiiiiiijKKKKKKKKKKWWWWWWWWWWWWWWWWWWWWWt;i;;;;i;DDDDDDGi;;;;;;;;:.............EDf;,,,;,G;;;;;;;;;;;;;;;,,,,,,,,,, *
	 *fjt:......:,,,,,,;LDDDEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKWWWWKWWWW####KKKKKiiiiiiiiiiijKEKKWKKKKKKKWWWWWWWWWWWWWWWWWWWWWWiLiii;i;DEEEEDDE;i;;;;;;;;;:..........EDi,;;;;;L;;;;;;;;;;;;;;;;;;,,,,,,, *
	 *fjt:......:,,,,,;EDDDEEKEEEEEEEEEKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKWWWWKKWWW##W#KWKKWEiiiiiijGKKKKKWWKKKKKKKKWWWWWWWWWWWWWWWWWWWWWWKi;iiiiDDEEEEEEDEi;;;;;;;;;;;;;,:.....ED;;;;;;;j;;;;;;;;;;;;;;;;;;;;;;;,, *
	 *fjt:.....t,,,,,;DDDDEEEKEEEEEEEEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWKKKWWWW##WKWKKWKiiiKKKKKKKKKWWKKKKKKKKWWWWWWWWWWWWWWW#WWWWWWWWWiiiiifLEEEEEEEEDi;i;;;;;;;;;;;;.....DD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; *
	 *fjt:.....G,,,,,GDDDEEEEEEEEEEEEKKKKKKKKKKKKKKKKWKKKKKKKKKKKKKKKWWWKKKWWW###WKWKKWKitKKKKKKKKKWKKKKKKKKKKWWWWWWWWWWWWWW###WWWWWWWWEiiiiiiiEEEEEEEEDGiiii;;;;;;;;;.....GD;;;;;;;i;;;;;;;;;;;;;;;;;;;;;;;;; *
	 *fjt:.....L,,,,;GDDDEEEEEEEEEEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKWWWWWDGWWW###KKWWKWKKKKKKKKKKKKKKKKKKKKKKKWWWWWWWWWWWWW####WWWWWWWWWiiiiiiiiEEEEEEEEEEDi;i;;;;;;;;.....Lj;;;;;;i;iiiiii;;;;;;ii;;;;;;;;;;; *
	 ***********************************************************************************************************************************************************************************************************/

	void sort(int a[]) {
		ArrayList<Integer> list=new ArrayList<>();
		for(int x: a) list.add(x);
		Collections.sort(list);
		for(int i=0;i<a.length;i++) a[i]=list.get(i);
	}
	void sort(long a[]) {
		ArrayList<Long> list=new ArrayList<>();
		for(long x: a) list.add(x);
		Collections.sort(list);
		for(int i=0;i<a.length;i++) a[i]=list.get(i);
	}
	void ruffleSort(int a[]) {
		Random rand=new Random();
		int n=a.length;
		for(int i=0;i<n;i++) {
			int j=rand.nextInt(n);
			int temp=a[i];
			a[i]=a[j];
			a[j]=temp;
		}
		Arrays.sort(a);
	}
	void ruffleSort(long a[]) {
		Random rand=new Random();
		int n=a.length;
		for(int i=0;i<n;i++) {
			int j=rand.nextInt(n);
			long temp=a[i];
			a[i]=a[j];
			a[j]=temp;
		}
		Arrays.sort(a);
	}

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;
        public FastReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }
        String next() {
            while (st==null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }
        double nextDouble() {
            return Double.parseDouble(next());
        }
        String nextLine() {
            String s="";
            try {
                s=br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return s;
        }
    }

	long fact[];
	long invFact[];
	void init(int n) {
		fact=new long[n+1];
		invFact=new long[n+1];
		fact[0]=1;
		for(int i=1;i<=n;i++) {
			fact[i]=mul(i,fact[i-1]);
		}
		invFact[n]=power(fact[n],mod-2);
		for(int i=n-1;i>=0;i--) {
			invFact[i]=mul(invFact[i+1],i+1);
		}
	}

	long nCr(int n, int r) {
		if(n<r || r<0) return 0;
		return mul(fact[n],mul(invFact[r],invFact[n-r]));
	}

	long mul(long a, long b) {
		return a*b%mod;
	}
	long add(long a, long b) {
		return (a+b)%mod;
	}

	long power(long x, long y) {
		long gg=1;
		while(y>0) {
			if(y%2==1) gg=mul(gg,x);
			x=mul(x,x);
			y/=2;
		}
		return gg;
	}

    // Functions
	static long gcd(long a, long b) {
		return b==0?a:gcd(b,a%b);
	}
	static int gcd(int a, int b) {
		return b==0?a:gcd(b,a%b);
	}

	void print(int a[]) {
		int n=a.length;
		for(int i=0;i<n;i++) out.print(a[i]+" ");
	}

	void print(long a[]) {
		int n=a.length;
		for(int i=0;i<n;i++) out.print(a[i]+" ");
	}

    //Input Arrays
    static void input(long a[], int n) {
		for(int i=0;i<n;i++) {
			a[i]=inp.nextLong();
		}
	}
	static void input(int a[], int n) {
		for(int i=0;i<n;i++) {
			a[i]=inp.nextInt();
		}
	}
	static void input(String s[],int n) {
		for(int i=0;i<n;i++) {
			s[i]=inp.next();
		}
	}
	static void input(int a[][], int n, int m) {
		for(int i=0;i<n;i++) {
			for(int j=0;j<m;j++) {
				a[i][j]=inp.nextInt();
			}
		}
	}
	static void input(long a[][], int n, int m) {
		for(int i=0;i<n;i++) {
			for(int j=0;j<m;j++) {
				a[i][j]=inp.nextLong();
			}
		}
	}

}


import java.util.*;
import java.io.*;

public class D_1421 {
	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		PrintWriter pw = new PrintWriter(System.out);

		int t = sc.nextInt();
		while(t-->0) {
			int x = sc.nextInt(), y = sc.nextInt();
			int c1 = sc.nextInt(), c2 = sc.nextInt(), c3 = sc.nextInt(), c4 = sc.nextInt(), c5 = sc.nextInt(), c6 = sc.nextInt();
			long ans = 0;

			if(x == 0 && y == 0) {
				ans = 0;
			} else if(x == 0 && y > 0) {
				// up
				ans = 1l * Math.min(c1 + c3, c2) * y;
			} else if(x == 0 && y < 0) {
				// down
				ans = 1l * Math.min(c4 + c6, c5) * -y;
			} else if(y == 0 && x > 0) {
				// right
				ans = 1l * Math.min(c1 + c5, c6) * x;
			} else if(y == 0 && x < 0) {
				// left
				ans = 1l * Math.min(c2 + c4, c3) * -x;
			} else if(x > 0 && y > 0) {
				//1st
				int min = Math.min(x, y);
				ans = 1l * Math.min(c2 + c6, c1) * min;
				x -= min;
				y -= min;
				if(x == 0 && y == 0) {
					ans += 0;
				} else if(x == 0 && y > 0) {
					// up
					ans += 1l * Math.min(c1 + c3, c2) * y;
				} else if(x == 0 && y < 0) {
					// down
					ans += 1l * Math.min(c4 + c6, c5) * -y;
				} else if(y == 0 && x > 0) {
					// right
					ans += 1l * Math.min(c1 + c5, c6) * x;
				} else if(y == 0 && x < 0) {
					// left
					ans += 1l * Math.min(c2 + c4, c3) * -x;
				}
			} else if(x > 0 && y < 0) {
				//4th
				// down
				ans = 1l * Math.min(c4 + c6, c5) * -y;
				// right
				ans += 1l * Math.min(c1 + c5, c6) * x;
			} else if(x < 0 && y > 0) {
				//2nd
				// up
				ans = 1l * Math.min(c1 + c3, c2) * y;
				// left
				ans += 1l * Math.min(c2 + c4, c3) * -x;
			} else {
				//3rd
				int min = Math.min(-x, -y);
				ans = 1l * Math.min(c3 + c5, c4) * min;
				x += min;
				y += min;
				if(x == 0 && y == 0) {
					ans += 0;
				} else if(x == 0 && y > 0) {
					// up
					ans += 1l * Math.min(c1 + c3, c2) * y;
				} else if(x == 0 && y < 0) {
					// down
					ans += 1l * Math.min(c4 + c6, c5) * -y;
				} else if(y == 0 && x > 0) {
					// right
					ans += 1l * Math.min(c1 + c5, c6) * x;
				} else if(y == 0 && x < 0) {
					// left
					ans += 1l * Math.min(c2 + c4, c3) * -x;
				}
			}

			pw.println(ans);
		}

		pw.flush();
	}

	public static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(next());
		}

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

		public long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		public int[] nextIntArray(int n) throws IOException {
			int[] array = new int[n];
			for (int i = 0; i < n; i++)
				array[i] = nextInt();
			return array;
		}

		public Integer[] nextIntegerArray(int n) throws IOException {
			Integer[] array = new Integer[n];
			for (int i = 0; i < n; i++)
				array[i] = new Integer(nextInt());
			return array;
		}

		public long[] nextLongArray(int n) throws IOException {
			long[] array = new long[n];
			for (int i = 0; i < n; i++)
				array[i] = nextLong();
			return array;
		}

		public double[] nextDoubleArray(int n) throws IOException {
			double[] array = new double[n];
			for (int i = 0; i < n; i++)
				array[i] = nextDouble();
			return array;
		}

		public static int[] shuffle(int[] a) {
			int n = a.length;
			Random rand = new Random();
			for (int i = 0; i < n; i++) {
				int tmpIdx = rand.nextInt(n);
				int tmp = a[i];
				a[i] = a[tmpIdx];
				a[tmpIdx] = tmp;
			}
			return a;
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}


import java.util.*;
import java.io.*;

public class Main {
    public static void main(String args[]) {new Main().run();}

    FastReader in = new FastReader();
    PrintWriter out = new PrintWriter(System.out);
    void run(){
        for(int q=ni();q>0;q--){
            work();
        }
        out.flush();
    }
    long mod=1000000007;
    long gcd(long a,long b) {
        return a==0?b:gcd(b%a,a);
    }

    void work() {
        long[] end=na(2);
        long[][] dir=new long[][]{{1,1},{0,1},{-1,0},{-1,-1},{0,-1},{1,0}};
        long[] cost=na(6);
        long ret=Long.MAX_VALUE;
        for(int i=0;i<6;i++){
            long[] d=dir[i];
            if(sign(end[0],d[0])){
                long x=end[0],y=end[1];
                long r=0;
                r+=Math.abs(x)*cost[i];
                long dy=y-dir[i][1]*Math.abs(end[0]);
                if(dy>0){
                    r+=Math.abs(cost[1]*dy);
                }else{
                    r+=Math.abs(cost[4]*dy);
                }

                ret=Math.min(ret,r);
            }

            if(sign(end[1],d[1])){
                long x=end[0],y=end[1];
                long r=0;
                r+=cost[i]*Math.abs(y);
                long dx=x-dir[i][0]*Math.abs(end[1]);
                if(dx>0){
                    r+=Math.abs(cost[5]*dx);
                }else{
                    r+=Math.abs(cost[2]*dx);
                }

                ret=Math.min(ret,r);
            }
        }
        out.println(ret);
    }

    private boolean sign(long a, long b) {
        if((a>0&&b>0)||(a<0&&b<0))return true;
        return false;
    }

    private ArrayList<long[]>[] ngw(int n, int m) {
        ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n];
        for(int i=0;i<n;i++) {
            graph[i]=new ArrayList<>();
        }
        for(int i=1;i<=m;i++) {
            long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong();
            graph[(int)s].add(new long[] {e,w,i});
            graph[(int)e].add(new long[] {s,w});
        }
        return graph;
    }

    private int ni() {
        return in.nextInt();
    }

    private long nl() {
        return in.nextLong();
    }

    private String ns() {
        return in.next();
    }

    private long[] na(int n) {
        long[] A=new long[n];
        for(int i=0;i<n;i++) {
            A[i]=in.nextLong();
        }
        return A;
    }
    private int[] nia(int n) {
        int[] A=new int[n];
        for(int i=0;i<n;i++) {
            A[i]=in.nextInt();
        }
        return A;
    }
}

class FastReader
{
    BufferedReader br;
    StringTokenizer st;

    public FastReader()
    {
        br=new BufferedReader(new InputStreamReader(System.in));
    }

    public String next()
    {
        while(st==null || !st.hasMoreElements())//回车，空行情况
        {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    public int nextInt()
    {
        return Integer.parseInt(next());
    }

    public long nextLong()
    {
        return Long.parseLong(next());
    }
}


import java.util.*;
import java.io.*;

public class Main {
    public static void main(String args[]) {new Main().run();}

    FastReader in = new FastReader();
    PrintWriter out = new PrintWriter(System.out);
    void run(){
        for(int q=ni();q>0;q--){
            work();
        }
        out.flush();
    }
    long mod=1000000007;
    long gcd(long a,long b) {
        return a==0?b:gcd(b%a,a);
    }

    void work() {
        long[] end=na(2);
        long[][] dir=new long[][]{{1,1},{0,1},{-1,0},{-1,-1},{0,-1},{1,0}};
        long[] cost=na(6);
        long ret=Long.MAX_VALUE;
        if(end[0]==0&&end[1]==0){
            out.println(0);
            return;
        }
        for(int i=0;i<6;i++){
            long[] d=dir[i];
            if(sign(end[0],d[0])){
                long x=end[0],y=end[1];
                long r=0;
                r+=Math.abs(x)*cost[i];
                long dy=y-dir[i][1]*Math.abs(end[0]);
                if(dy>0){
                    r+=Math.abs(cost[1]*dy);
                }else{
                    r+=Math.abs(cost[4]*dy);
                }

                ret=Math.min(ret,r);
            }

            if(sign(end[1],d[1])){
                long x=end[0],y=end[1];
                long r=0;
                r+=cost[i]*Math.abs(y);
                long dx=x-dir[i][0]*Math.abs(end[1]);
                if(dx>0){
                    r+=Math.abs(cost[5]*dx);
                }else{
                    r+=Math.abs(cost[2]*dx);
                }

                ret=Math.min(ret,r);
            }
        }
        out.println(ret);
    }

    private boolean sign(long a, long b) {
        if((a>0&&b>0)||(a<0&&b<0))return true;
        return false;
    }

    private ArrayList<long[]>[] ngw(int n, int m) {
        ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n];
        for(int i=0;i<n;i++) {
            graph[i]=new ArrayList<>();
        }
        for(int i=1;i<=m;i++) {
            long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong();
            graph[(int)s].add(new long[] {e,w,i});
            graph[(int)e].add(new long[] {s,w});
        }
        return graph;
    }

    private int ni() {
        return in.nextInt();
    }

    private long nl() {
        return in.nextLong();
    }

    private String ns() {
        return in.next();
    }

    private long[] na(int n) {
        long[] A=new long[n];
        for(int i=0;i<n;i++) {
            A[i]=in.nextLong();
        }
        return A;
    }
    private int[] nia(int n) {
        int[] A=new int[n];
        for(int i=0;i<n;i++) {
            A[i]=in.nextInt();
        }
        return A;
    }
}

class FastReader
{
    BufferedReader br;
    StringTokenizer st;

    public FastReader()
    {
        br=new BufferedReader(new InputStreamReader(System.in));
    }

    public String next()
    {
        while(st==null || !st.hasMoreElements())//回车，空行情况
        {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    public int nextInt()
    {
        return Integer.parseInt(next());
    }

    public long nextLong()
    {
        return Long.parseLong(next());
    }
}


import java.io.*;
import java.util.*;
public class D {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        int tst = Integer.parseInt(br.readLine());
        while(tst-->0){
            String[] str = br.readLine().split(" ");
            int x = Integer.parseInt(str[0]), y = Integer.parseInt(str[1]);
            long[] cost = new long[7];
            StringTokenizer st = new StringTokenizer(br.readLine());
            for(int i = 1; i<=6; i++){
                cost[i] = Integer.parseInt(st.nextToken());
            }
            long[] minCost = new long[7];
            minCost[1] = Math.min(cost[1], cost[6]+cost[2]);
            minCost[2] = Math.min(cost[2], cost[1]+cost[3]);
            minCost[3] = Math.min(cost[3], cost[2]+cost[4]);
            minCost[4] = Math.min(cost[4], cost[3]+cost[5]);
            minCost[5] = Math.min(cost[5], cost[4]+cost[6]);
            minCost[6] = Math.min(cost[6], cost[5]+cost[1]);
            long ans = 0;
            if(x>=0 && y>=0){
                long d = Math.min(x, y);
                ans += d*minCost[1];
                x-=d;
                y-=d;
                if(x>0) ans += x*minCost[6];
                else if(y>0) ans+=y*minCost[2];
            }
            else if(x>=0){
                y = -y;
                ans += x*minCost[6];
                ans += y*minCost[5];
            }
            else if(y>=0){
                x = -x;
                ans += x*minCost[3];
                ans += y*minCost[2];
            }
            else{
                x = -x;
                y = -y;
                long d = Math.min(x, y);
                ans += d*minCost[4];
                x-=d;
                y-=d;
                if(x>0) ans+=x*minCost[3];
                else if(y>0) ans+=y*minCost[5];
            }
            sb.append(ans).append('\n');
        }
        System.out.println(sb);
    }
}


import java.io.*;
import java.util.*;
public class D {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        int tst = Integer.parseInt(br.readLine());
        while(tst-->0){
            String[] str = br.readLine().split(" ");
            int x = Integer.parseInt(str[0]), y = Integer.parseInt(str[1]);
            int[] cost = new int[7];
            StringTokenizer st = new StringTokenizer(br.readLine());
            for(int i = 1; i<=6; i++){
                cost[i] = Integer.parseInt(st.nextToken());
            }
            int[] minCost = new int[7];
            minCost[1] = Math.min(cost[1], cost[6]+cost[2]);
            minCost[2] = Math.min(cost[2], cost[1]+cost[3]);
            minCost[3] = Math.min(cost[3], cost[2]+cost[4]);
            minCost[4] = Math.min(cost[4], cost[3]+cost[5]);
            minCost[5] = Math.min(cost[5], cost[4]+cost[6]);
            minCost[6] = Math.min(cost[6], cost[5]+cost[1]);
            long ans = 0;
            if(x>=0 && y>=0){
                int d = Math.min(x, y);
                ans += (long)d*minCost[1];
                x-=d;
                y-=d;
                if(x>0) ans += x*cost[3];
                else if(y>0) ans+=y*cost[5];
            }
            else if(x>=0){
                y = -y;
                ans += x*cost[6];
                ans += y*cost[5];
            }
            else if(y>=0){
                x = -x;
                ans += x*cost[3];
                ans += y*cost[2];
            }
            else{
                x = -x;
                y = -y;
                int d = Math.min(x, y);
                ans += (long)d*minCost[4];
                x-=d;
                y-=d;
                if(x>0) ans+=x*cost[3];
                else if(y>0) ans+=y*cost[5];
            }
            sb.append(ans).append('\n');
        }
        System.out.println(sb);
    }
}


import java.io.*;
import java.util.*;
public class D {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        int tst = Integer.parseInt(br.readLine());
        while(tst-->0){
            String[] str = br.readLine().split(" ");
            int x = Integer.parseInt(str[0]), y = Integer.parseInt(str[1]);
            int[] cost = new int[7];
            StringTokenizer st = new StringTokenizer(br.readLine());
            for(int i = 1; i<=6; i++){
                cost[i] = Integer.parseInt(st.nextToken());
            }
            int[] minCost = new int[7];
            minCost[1] = Math.min(cost[1], cost[6]+cost[2]);
            minCost[2] = Math.min(cost[2], cost[1]+cost[3]);
            minCost[3] = Math.min(cost[3], cost[2]+cost[4]);
            minCost[4] = Math.min(cost[4], cost[3]+cost[5]);
            minCost[5] = Math.min(cost[5], cost[4]+cost[6]);
            minCost[6] = Math.min(cost[6], cost[5]+cost[1]);
            long ans = 0;
            if(x>=0 && y>=0){
                int d = Math.min(x, y);
                ans += (long)d*minCost[1];
                x-=d;
                y-=d;
                if(x>0) ans += x*minCost[3];
                else if(y>0) ans+=y*minCost[5];
            }
            else if(x>=0){
                y = -y;
                ans += x*minCost[6];
                ans += y*minCost[5];
            }
            else if(y>=0){
                x = -x;
                ans += x*minCost[3];
                ans += y*minCost[2];
            }
            else{
                x = -x;
                y = -y;
                int d = Math.min(x, y);
                ans += (long)d*minCost[4];
                x-=d;
                y-=d;
                if(x>0) ans+=x*minCost[3];
                else if(y>0) ans+=y*minCost[5];
            }
            sb.append(ans).append('\n');
        }
        System.out.println(sb);
    }
}


#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define endl "\n"
#define qq cout<<" here ";
#define int long long
#define ff(n) for(int i=0;i<n;i++)
#define For(i, a, b) for(ll i=(a);i<=(b);i++)
#define pb(i) push_back(i)
#define mp(i,j) make_pair(i,j)
#define vi vector<ll>
int mod=1e9+7; int N=1e5+5;
int absl(int x,int y){
    if(x>y){return x-y;}
    return y-x;
}
int powf(int a,int m){
    if(m<=0){return 1;}
    int t=powf(a,m/2); t=(t*t)%mod;
    if(m&1){return (a*t)%mod;}
    return t;
}

void solve(){

 int x,y;cin>>x>>y;
 int c1[7]; int c[7];
 ff(6){cin>>c1[i+1];}
 c[1]=min(c1[1],c1[6]+c1[2]);
 c[2]=min(c1[3]+c1[1],c1[2]);
 c[3]=min(c1[3],c1[2]+c1[4]);
 c[4]=min(c1[4],c1[5]+c1[3]);
 c[5]=min(c1[5],c1[6]+c1[4]);
 c[6]=min(c1[6],c1[5]+c1[1]);

 int res=0;
 int ans=0;

     if(y>0){ans+=y*c[2];}
     else if(y<0){ans+=-y*c[5];}
     if(x>0){ans+=x*c[6];}
     else{ans+=c[3]*(-x);}

 if(x>0&&y>0){
     res+=min(x,y)*c[1];
     if(x>=y){res+=absl(x,y)*c[6];}
     else{res+=absl(x,y)*c[2];}
 }
 else if(x<0&&y<0){
      res+=-max(x,y)*c[4];
      if(x<y){res+=c[3]*absl(x,y);}
      else{res+=c[5]*absl(x,y);}
 }
 else{
     ans=res;
 }

 cout<<min(ans,res)<<endl;

}

 main(){

    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    #endif

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int tc; tc=1;
    cin>>tc;
    while(tc--){
        solve();
    }
}


#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define endl "\n"
#define qq cout<<" here ";
#define int long long
#define ff(n) for(int i=0;i<n;i++)
#define For(i, a, b) for(ll i=(a);i<=(b);i++)
#define pb(i) push_back(i)
#define mp(i,j) make_pair(i,j)
#define vi vector<ll>
int mod=1e9+7; int N=1e5+5;
int absl(int x,int y){
    if(x>y){return x-y;}
    return y-x;
}
int powf(int a,int m){
    if(m<=0){return 1;}
    int t=powf(a,m/2); t=(t*t)%mod;
    if(m&1){return (a*t)%mod;}
    return t;
}

void solve(){

 int x,y;cin>>x>>y;
 int c1[7]; int c[7];
 ff(6){cin>>c1[i+1];}
 c[1]=min(c1[1],c1[6]+c1[2]);
 c[2]=min(c1[3]+c1[1],c1[2]);
 c[3]=min(c1[3],c1[2]+c1[4]);
 c[4]=min(c1[4],c1[5]+c1[3]);
 c[5]=min(c1[5],c1[6]+c1[4]);
 c[6]=min(c1[6],c1[5]+c1[1]);

 int res=0;
 if(x>0&&y>0){
     res+=min(x,y)*c[1];
     if(x>=y){res+=absl(x,y)*c[6];}
     else{res+=absl(x,y)*c[2];}
 }
 else if(x<0&&y<0){
      res+=-max(x,y)*c[4];
     // cout<<res<<endl;
      if(x<y){res+=c[3]*absl(x,y);}
      else{res+=c[5]*absl(x,y);}
      //cout<<c[5]<<endl;
    //  res=-res;

 }
 else if(x<0&&y>=0||y<0&&x>=0){
     //cout<<c[6]<<endl;
     if(y>0){res+=y*c[2];}
     else if(y<0){res+=-y*c[5];}
     //cout<<res<<endl;
     if(x>0){res+=x*c[6];}
     else{res+=c[3]*(-x);}
 }
 cout<<res<<endl;

}

 main(){

    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    #endif

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int tc; tc=1;
    cin>>tc;
    while(tc--){
        solve();
    }
}


#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <iomanip>
using namespace std;
#define assem99 ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define ull unsigned long long
#define ld long double
#define ii pair<int, int>
#define f(i,a,b) for(int i=a; i<b; i++)
#define F first
#define S second
#define sz(a) (int)(a).size()
#define ReadFile freopen("input.txt","r",stdin)
#define WriteFile freopen("output.txt","w",stdout)
int x[] = { 0, -1, 0, 1, -1, 1, -1, 1 };
int y[] = { -1, 0, 1, 0, 1, -1, -1, 1 };
const int MOD = 1e9 + 7, N = 2e5 + 5;
const double pi = acos(-1);

char arr[150][150];
int n, m, leftt[200], rightt[200];

int getLeft(int col)
{
	f(i, 0, m + 2) if (arr[col][i] == '1') return i;
	return -1;
}

int getRight(int col)
{
	for (int i = m + 1; i >= 0; i--) if (arr[col][i] == '1') return i;
	return -1;
}

int main()
{
	assem99;

	int hi = 1e9;
	cin >> n >> m;
	f(i, 0, n) f(j, 0, m + 2)
	{
		cin >> arr[i][j];
		if (arr[i][j] == '1' && hi == 1e9) hi = i;
	}
	for (int i = n - 1; i >= 0; i--) leftt[i] = getLeft(i), rightt[i] = getRight(i);
	int ans = rightt[n - 1], curPos = rightt[n - 1];
	for(int i = n - 2; i >= 0; i--)
	{
		if (leftt[i] == -1) continue;
		int l = curPos + rightt[i] + 1;
		int r = ((m + 1) - curPos);
		r += ((m + 1) - leftt[i]) + 1;
		if (l < r)
		{
			ans += l;
			curPos = rightt[i];
		}
		else
		{
			ans += r;
			curPos = leftt[i];
		}
	}
	cout << ans;

	return 0;
}


#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <iomanip>
using namespace std;
#define assem99 ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define ull unsigned long long
#define ld long double
#define ii pair<int, int>
#define f(i,a,b) for(int i=a; i<b; i++)
#define F first
#define S second
#define sz(a) (int)(a).size()
#define ReadFile freopen("input.txt","r",stdin)
#define WriteFile freopen("output.txt","w",stdout)
int x[] = { 0, -1, 0, 1, -1, 1, -1, 1 };
int y[] = { -1, 0, 1, 0, 1, -1, -1, 1 };
const int MOD = 1e9 + 7, N = 2e5 + 5;
const double pi = acos(-1);

int ans = 1e9, n, m, leftt[200], rightt[200], hi;

int getLeft(int col, string arr)
{
	f(i, 0, m) if (arr[i] == '1') return i;
	return -1;
}

int getRight(int col, string arr)
{
	for (int i = m - 1; i >= 0; i--) if (arr[i] == '1') return i;
	return -1;
}

void solve(int pos, int curAns, int row)
{
	if (row == hi - 1)
	{
		ans = min(ans, curAns);
		return;
	}
	//cout << (pos + leftt[row] + 1);
	if(rightt[row] != -1)solve(rightt[row], curAns + (pos + rightt[row] + 1), row - 1); // left
	else solve(0, curAns + 1 + pos, row - 1);
	if (leftt[row] != -1)solve(leftt[row], curAns + (((m - pos) - 1) + (m - leftt[row])), row - 1); // right
	else solve(m - 1, curAns + 1 + (m - pos), row - 1);
}

int main()
{
	assem99;

	hi = 0;
	bool zero = true;
	cin >> n >> m; m += 2;
	f(i, 0, n)
	{
		string s; cin >> s;
		leftt[i] = getLeft(i, s);
		rightt[i] = getRight(i, s);
		if (leftt[i] != -1 && zero) hi = i, zero = false;
	}
	if (hi == n - 1) cout << "0" << endl;
	solve(max(0, rightt[n - 1]), rightt[n - 1], n - 2);
	if(ans >= 0)cout << ans;
	else cout << "0";

	return 0;
}


#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <iomanip>
using namespace std;
#define assem99 ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define ull unsigned long long
#define ld long double
#define ii pair<int, int>
#define f(i,a,b) for(int i=a; i<b; i++)
#define F first
#define S second
#define sz(a) (int)(a).size()
#define ReadFile freopen("input.txt","r",stdin)
#define WriteFile freopen("output.txt","w",stdout)
int x[] = { 0, -1, 0, 1, -1, 1, -1, 1 };
int y[] = { -1, 0, 1, 0, 1, -1, -1, 1 };
const int MOD = 1e9 + 7, N = 2e5 + 5;
const double pi = acos(-1);

char arr[150][150];
int n, m, leftt[200], rightt[200];

int getLeft(int col)
{
	f(i, 0, m + 2) if (arr[col][i] == '1') return i;
	return -1;
}

int getRight(int col)
{
	for (int i = m + 1; i >= 0; i--) if (arr[col][i] == '1') return i;
	return -1;
}

int main()
{
	assem99;

	int hi = 1e9;
	cin >> n >> m;
	f(i, 0, n) f(j, 0, m + 2)
	{
		cin >> arr[i][j];
		if (arr[i][j] == '1' && hi == 1e9) hi = i;
	}
	for (int i = n - 1; i >= 0; i--) leftt[i] = getLeft(i), rightt[i] = getRight(i);
	int ans = rightt[n - 1], curPos = rightt[n - 1];
	for(int i = n - 2; i >= 0; i--)
	{
		if (leftt[i] == -1) continue;
		int l = curPos + rightt[i] + 1;
		int r = ((m + 1) - curPos);
		r += ((m + 1) - leftt[i]) + 1;
		if (l < r)
		{
			ans += l;
			curPos = rightt[i];
		}
		else
		{
			ans += r;
			curPos = leftt[i];
		}
	}
	if (ans <= -1) cout << 0;
	else cout << ans;

	return 0;
}


#include <iostream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <iomanip>
using namespace std;
#define assem99 ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define ull unsigned long long
#define ld long double
#define ii pair<int, int>
#define f(i,a,b) for(int i=a; i<b; i++)
#define F first
#define S second
#define sz(a) (int)(a).size()
#define ReadFile freopen("input.txt","r",stdin)
#define WriteFile freopen("output.txt","w",stdout)
int x[] = { 0, -1, 0, 1, -1, 1, -1, 1 };
int y[] = { -1, 0, 1, 0, 1, -1, -1, 1 };
const int MOD = 1e9 + 7, N = 2e5 + 5;
const double pi = acos(-1);

int ans = 1e9, n, m, leftt[200], rightt[200], hi;

int getLeft(int col, string arr)
{
	f(i, 0, m) if (arr[i] == '1') return i;
	return -1;
}

int getRight(int col, string arr)
{
	for (int i = m - 1; i >= 0; i--) if (arr[i] == '1') return i;
	return -1;
}

void solve(int pos, int curAns, int row)
{
	if (row == hi - 1)
	{
		ans = min(ans, curAns);
		return;
	}
	//cout << (pos + leftt[row] + 1);
	if(rightt[row] != -1)solve(rightt[row], curAns + (pos + rightt[row] + 1), row - 1); // left
	else solve(0, curAns + 1 + pos, row - 1);
	if (leftt[row] != -1)solve(leftt[row], curAns + (((m - pos) - 1) + (m - leftt[row])), row - 1); // right
	else solve(m - 1, curAns + 1 + (m - pos), row - 1);
}

int main()
{
	assem99;

	hi = -1;
	bool zero = true;
	cin >> n >> m; m += 2;
	f(i, 0, n)
	{
		string s; cin >> s;
		leftt[i] = getLeft(i, s);
		rightt[i] = getRight(i, s);
		if (leftt[i] != -1 && zero) hi = i, zero = false;
	}

	if (zero) cout << "0";
	else
	{
		solve(max(0, rightt[n - 1]),rightt[n - 1], n - 2);
		if(ans >= 0)cout << ans;
		else cout << "0";
	}
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define int 		long long
#define vi 			vector <int>
#define si 			set <int>
#define pii 		pair<int,int>
#define fr(n) 		for(__typeof(n) i=0;i<n;i++)
#define rep(i,a,b) 	for(__typeof(b) i=a;i<b;i++)
#define repi(i,b,a) for(__typeof(a) i=b;i>=a;i--)
#define tr(a) 		for(auto it=a.begin();it!=a.end();it++)
#define pb 			push_back
#define mp 			make_pair
#define F 			first
#define S 			second
#define FAST 		ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define time_passed	1.0 * clock() / CLOCKS_PER_SEC

int n,m,l[15],r[15],dp[15][2];
string s[15];

int fun(int pos,int flag)
{
	if(pos==(n-1) and l[pos]==0)
		return -1;
	if(dp[pos][flag]!=-1) return dp[pos][flag];
	if(l[pos]==0)
	{
		return fun(pos+1,flag);
	}
	if(pos==n-1)
	{
		if(flag==0)
			return r[pos];
		else
			return m+1-l[pos];
	}
	int ans;
	if(flag==0)
	{
		if(m%2 == 1 and r[pos]==(m+1)/2)
			ans = m+1+min(fun(pos+1,0ll),fun(pos+1,1))+1;
		else if(r[pos]<=m/2)
			ans =  2*r[pos] + fun(pos+1,flag)+1;
		else
			ans = m+1 + fun(pos+1,!flag)+1;
	}
	else
	{
		if(m%2 == 1 and l[pos]==(m+1)/2)
			ans=m+1+min(fun(pos+1,0ll),fun(pos+1,1))+1;
		else if(l[pos]>(m+1)/2)
			ans = 2*(m+1-l[pos]) + fun(pos+1,flag)+1;
		else
			ans = m+1 + fun(pos+1,!flag)+1;
	}
	return dp[pos][flag]=ans;
}

void solve()
{
	cin>>n>>m;
	int val=0;;
	fr(n)
	{
		cin>>s[n-i-1];
		l[n-i-1]=r[n-1-i]=0;
		val=0;
		rep(j,1,m+1)
		{
			if(s[n-1-i][j]=='1')
			{
				if(val==0){
					l[n-1-i]=j;
					val=1;
				}
				r[n-1-i]=j;
			}
		}
	}
	for(int i=(n-1);i>=0;i--)
	{
		if(l[i]==0)
			n--;
		else
			break;
	}
	fr(n)
	{
		memset(dp[i],-1,sizeof(dp[i]));
	}
	int ans=0;
	if(n>0)
		ans=fun(0,0);
	cout<<ans;
}

signed main()
{
	FAST
	int test=1;
	//cin>>test;
	while(test--)
	{
		solve();
	}
	cerr<<endl<<"Time elapsed : "<<time_passed<<endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define int 		long long
#define vi 			vector <int>
#define si 			set <int>
#define pii 		pair<int,int>
#define fr(n) 		for(__typeof(n) i=0;i<n;i++)
#define rep(i,a,b) 	for(__typeof(b) i=a;i<b;i++)
#define repi(i,b,a) for(__typeof(a) i=b;i>=a;i--)
#define tr(a) 		for(auto it=a.begin();it!=a.end();it++)
#define pb 			push_back
#define mp 			make_pair
#define F 			first
#define S 			second
#define FAST 		ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define time_passed	1.0 * clock() / CLOCKS_PER_SEC

int n,m,l[15],r[15],dp[15][2];
string s[15];

int fun(int pos,int flag)
{
	if(dp[pos][flag]!=-1) return dp[pos][flag];
	if(pos==n-1)
	{
		if(flag==0)
			return r[pos];
		else
			return m+1-l[pos];
	}
	int ans1,ans2;
	if(flag==0)
	{
		ans1 =  2*r[pos] + fun(pos+1,flag)+1;
		ans2 = m+1 + fun(pos+1,!flag)+1;
	}
	else
	{
		ans1 = 2*(m+1-l[pos]) + fun(pos+1,flag)+1;
		ans2 = m+1 + fun(pos+1,!flag)+1;
	}
	return dp[pos][flag]=min(ans1,ans2);
}

void solve()
{
	cin>>n>>m;
	int val=0;;
	fr(n)
	{
		cin>>s[n-i-1];
		l[n-i-1]=m+1;
		r[n-1-i]=0;
		val=0;
		rep(j,1,m+1)
		{
			if(s[n-1-i][j]=='1')
			{
				if(val==0){
					l[n-1-i]=j;
					val=1;
				}
				r[n-1-i]=j;
			}
		}
	}
	for(int i=(n-1);i>=0;i--)
	{
		if(r[i]==0)
			n--;
		else
			break;
	}
	fr(n)
	{
		memset(dp[i],-1,sizeof(dp[i]));
	}
	int ans=0;
	if(n>0)
		ans=fun(0,0);
	cout<<ans;
}

signed main()
{
	FAST
	int test=1;
	//cin>>test;
	while(test--)
	{
		solve();
	}
	cerr<<endl<<"Time elapsed : "<<time_passed<<endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define int 		long long
#define vi 			vector <int>
#define si 			set <int>
#define pii 		pair<int,int>
#define fr(n) 		for(__typeof(n) i=0;i<n;i++)
#define rep(i,a,b) 	for(__typeof(b) i=a;i<b;i++)
#define repi(i,b,a) for(__typeof(a) i=b;i>=a;i--)
#define tr(a) 		for(auto it=a.begin();it!=a.end();it++)
#define pb 			push_back
#define mp 			make_pair
#define F 			first
#define S 			second
#define FAST 		ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define time_passed	1.0 * clock() / CLOCKS_PER_SEC

int n,m,l[15],r[15],dp[15][2];
string s[15];

int fun(int pos,int flag)
{
	if(dp[pos][flag]!=-1) return dp[pos][flag];
	if(pos==n-1)
	{
		if(flag==0)
			return r[pos];
		else
			return m+1-l[pos];
	}
	int ans1,ans2;
	if(flag==0)
	{
		ans1 =  2*r[pos] + fun(pos+1,flag)+1;
		ans2 = m+1 + fun(pos+1,!flag)+1;
	}
	else
	{
		ans1 = 2*(m+1-l[pos]) + fun(pos+1,flag)+1;
		ans2 = m+1 + fun(pos+1,!flag)+1;
	}
	return dp[pos][flag]=min(ans1,ans2);
}

void solve()
{
	cin>>n>>m;
	int val=0;;
	fr(n)
	{
		cin>>s[n-i-1];
		l[n-i-1]=r[n-1-i]=0;
		val=0;
		rep(j,1,m+1)
		{
			if(s[n-1-i][j]=='1')
			{
				if(val==0){
					l[n-1-i]=j;
					val=1;
				}
				r[n-1-i]=j;
			}
		}
	}
	for(int i=(n-1);i>=0;i--)
	{
		if(l[i]==0)
			n--;
		else
			break;
	}
	fr(n)
	{
		memset(dp[i],-1,sizeof(dp[i]));
	}
	int ans=0;
	if(n>0)
		ans=fun(0,0);
	cout<<ans;
}

signed main()
{
	FAST
	int test=1;
	//cin>>test;
	while(test--)
	{
		solve();
	}
	cerr<<endl<<"Time elapsed : "<<time_passed<<endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define int 		long long
#define vi 			vector <int>
#define si 			set <int>
#define pii 		pair<int,int>
#define fr(n) 		for(__typeof(n) i=0;i<n;i++)
#define rep(i,a,b) 	for(__typeof(b) i=a;i<b;i++)
#define repi(i,b,a) for(__typeof(a) i=b;i>=a;i--)
#define tr(a) 		for(auto it=a.begin();it!=a.end();it++)
#define pb 			push_back
#define mp 			make_pair
#define F 			first
#define S 			second
#define FAST 		ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define time_passed	1.0 * clock() / CLOCKS_PER_SEC

int n,m,l[15],r[15],dp[15][2];
string s[15];

int fun(int pos,int flag)
{
	if(dp[pos][flag]!=-1) return dp[pos][flag];
	if(pos==n-1)
	{
		if(flag==0)
			return r[pos];
		else
			return m+1-l[pos];
	}
	int ans1,ans2;
	if(flag==0)
	{
		ans1 =  2*r[pos] + fun(pos+1,flag)+1;
		ans2 = m+1 + fun(pos+1,!flag)+1;
	}
	else
	{
		ans1 = 2*(m+1-l[pos]) + fun(pos+1,flag)+1;
		ans2 = m+1 + fun(pos+1,!flag)+1;
	}
	return dp[pos][flag]=min(ans1,ans2);
}

void solve()
{
	cin>>n>>m;
	int val=0;;
	fr(n)
	{
		cin>>s[n-i-1];
		l[n-i-1]=m+1;
		r[n-1-i]=0;
		val=0;
		rep(j,1,m+1)
		{
			if(s[n-1-i][j]=='1')
			{
				if(val==0){
					l[n-1-i]=j;
					val=1;
				}
				r[n-1-i]=j;
			}
		}
	}
	for(int i=(n-1);i>=0;i--)
	{
		if(l[i]==0)
			n--;
		else
			break;
	}
	fr(n)
	{
		memset(dp[i],-1,sizeof(dp[i]));
	}
	int ans=0;
	if(n>0)
		ans=fun(0,0);
	cout<<ans;
}

signed main()
{
	FAST
	int test=1;
	//cin>>test;
	while(test--)
	{
		solve();
	}
	cerr<<endl<<"Time elapsed : "<<time_passed<<endl;
	return 0;
}


#include<bits/stdc++.h>

using namespace std;

const int INF = 0x3f3f3f3f;
int n,m,l[200],r[200],lastf = INF,mid;

int solve(int f, int st, int k){
	int end = 0;
	if(st == 0)
		k += r[f],end = r[f];
	else
		k += m+1-l[f],end = l[f];

	if(f == lastf) return k;
	return min(solve(f-1,0,k + end + 1), solve(f-1,m+1,k + m+1-end + 1));
}

int main(){
	ios_base::sync_with_stdio(false),cin.tie(nullptr);
	memset(l,INF,sizeof l);

	cin >> n >> m;
	mid = (m+1)/2;
	for(int i = 1;i <= n;i++){
		string s;
		cin >> s;
		for(int j = 1;j < s.size()-1;j++){
			if(s[j] == '1'){
				l[i] = min(l[i],j);
				r[i] = max(r[i],j);
				lastf = min(lastf,i);
			}
		}
	}

	cout << (lastf == INF ? 0 : solve(n, 0, 0)) << endl;
}


#include<bits/stdc++.h>

using namespace std;

const int INF = 0x3f3f3f3f;
int n,m,l[200],r[200],lastf = INF,mid;

int solve(int f, int st, int k){
	if(f == -1) cout << "DEUMERDA",exit(0);
	int end = 0;
	if(st == 0)
		k += r[f],end = r[f];
	else
		k += m+1-l[f],end = l[f];

	if(f == lastf) return k;
	return min(solve(f-1,0,k + end + 1), solve(f-1,m+1,k + m+1-end + 1));
}

int main(){
	ios_base::sync_with_stdio(false),cin.tie(nullptr);
	memset(l,INF,sizeof l);

	cin >> n >> m;
	mid = (m+1)/2;
	for(int i = 1;i <= n;i++){
		string s;
		cin >> s;
		for(int j = 1;j < s.size()-1;j++){
			if(s[j] == '1'){
				l[i] = min(l[i],j);
				r[i] = max(r[i],j);
				lastf = min(lastf,i);
			}
		}
	}

	cout << solve(n, 0, 0) << endl;
}


#include<bits/stdc++.h>

using namespace std;

const int INF = 0x3f3f3f3f;
int n,m,l[20],r[20],lastf = INF,mid;

int solve(int f, int st, int k){
	int end = 0;

	if(r[f] == 0 && f != lastf) return solve(f-1,st,k+1);

	if(st == 0)
		k += r[f],end = r[f];
	else
		k += m+1-l[f],end = l[f];

	if(f == lastf) return k;
	return min(solve(f-1,0,k + end + 1), solve(f-1,m+1,k + m+1-end + 1));
}

int main(){
	ios_base::sync_with_stdio(false),cin.tie(nullptr);
	memset(l,INF,sizeof l);

	cin >> n >> m;
	mid = (m+1)/2;
	for(int i = 1;i <= n;i++){
		string s;
		cin >> s;
		for(int j = 1;j < s.size()-1;j++){
			if(s[j] == '1'){
				l[i] = min(l[i],j);
				r[i] = max(r[i],j);
				lastf = min(lastf,i);
			}
		}
	}

	cout << (lastf == INF ? 0 : solve(n, 0, 0)) << endl;
}


#include<bits/stdc++.h>

using namespace std;

const int INF = 0x3f3f3f3f;
int n,m,l[200],r[200],lastf = INF,mid;

int solve(int f, int st, int k){
	int end = 0;

	if(r[f] == 0) return solve(f-1,st,k);

	if(st == 0)
		k += r[f],end = r[f];
	else
		k += m+1-l[f],end = l[f];

	if(f == lastf) return k;
	return min(solve(f-1,0,k + end + 1), solve(f-1,m+1,k + m+1-end + 1));
}

int main(){
	ios_base::sync_with_stdio(false),cin.tie(nullptr);
	memset(l,INF,sizeof l);

	cin >> n >> m;
	mid = (m+1)/2;
	for(int i = 1;i <= n;i++){
		string s;
		cin >> s;
		for(int j = 1;j < s.size()-1;j++){
			if(s[j] == '1'){
				l[i] = min(l[i],j);
				r[i] = max(r[i],j);
				lastf = min(lastf,i);
			}
		}
	}

	cout << (lastf == INF ? 0 : solve(n, 0, 0)) << endl;
}


#include<bits/stdc++.h>

using namespace std;

const int INF = 0x3f3f3f3f;
int n,m,l[200],r[200],lastf = INF,mid;

int solve(int f, int st, int k){
	int end = 0;
	if(st == 0)
		k += r[f],end = r[f];
	else
		k += m+1-l[f],end = l[f];

	if(f == lastf) return k;
	return min(solve(f-1,0,k + end + 1), solve(f-1,m+1,k + m+1-end + 1));
}

int main(){
	ios_base::sync_with_stdio(false),cin.tie(nullptr);
	memset(l,INF,sizeof l);

	cin >> n >> m;
	mid = (m+1)/2;
	for(int i = 1;i <= n;i++){
		string s;
		cin >> s;
		for(int j = 1;j < s.size()-1;j++){
			if(s[j] == '1'){
				l[i] = min(l[i],j);
				r[i] = max(r[i],j);
				lastf = min(lastf,i);
			}
		}
	}

	cout << solve(n, 0, 0) << endl;
}


#include <bits/stdc++.h>
#define  na
#define ll long long
#define  ff first
#define ss second
#define vi vector<int>
#define vl vector<ll>
#define vll vector<pair<ll,ll> >
#define vvi vector<vector<int> >
#define vii vector<pair<int,int> >
#define pb push_back
#define inf 1000000000000000001
#define ninf -1000000007
#define mod 998244353
#define f(i,a,b) for(i=a;i<b;i++)
#define re0 return 0
using namespace std;

bool cmp(pair<pair<int,int>,int > &a,pair<pair<int,int>,int > &b)
{
      if(a.ff.ff==b.ff.ff)return a.ff.ss<b.ff.ss;
      return a.ff.ff<b.ff.ff;
}

ll nck(ll n,ll k)
{
	int i;
	ll sm=1;
	for(i=1;i<=k&&n;i++)sm*=n,n--,sm%=mod;
	for(i=1;i<=k;i++)sm/=i;
	return sm;
}
ll exp(ll j,ll n)
{
	ll i=n,res=1;

	while(j>0)
	{
		if(j&1)res*=i;
		res%=mod;
		 i=i*i;
		 i%=mod;
		j>>=1;
	}

	return res%mod;
}

int main()
{
	#ifdef ha
	freopen("input.txt","r",stdin);
	freopen("output.txt","w",stdout);
	#endif

  int T=1;

  //cin>>T;

  while(T--)
  {
  	int n,m,i,j;

  	cin>>n>>m;

  	int a[n][m+2];

  	f(i,0,n)
  	{  string s;
  	   cin>>s;
  		f(j,0,m+2)a[i][j]=s[j]-'0';
	}
	int b[n][2];

	for(i=n-1;i>-1;i--)
	{    int l=m+1,r=0;
		for(j=m+1;j>-1;j--)
		{
			if(a[i][j])break;
		}
		if(j>-1)r=j;
		for(j=0;j<m+2;j++)
		{
			if(a[i][j])break;
		}
		if(j<m+2)l=j;
		b[n-1-i][0]=m+1-l;
		b[n-1-i][1]=r;
	}
	int l[n],r[n];
	l[0]=2*b[0][1],r[0]=m+1;
	for(i=n-1;i>0;i--)
	{
		if(b[i][1])break;
	}
	int k=i;
	for(i=1;i<k;i++)
	{
		int p=2*b[i][1]+1,q=m+2;
		l[i]=min(p+l[i-1],r[i-1]+q);

		p=2*b[i][0]+1,q=m+2;
		r[i]=min(r[i-1]+p,l[i-1]+q);
	}
	int ansl,ansr;
	if(n>1)ansl=l[k-1]+b[k][1]+1,ansr=r[k-1]+b[k][0]+1;
	else ansl=b[0][1],ansr=ansl;
	cout<<min(ansl,ansr);

  }

 }


#include <bits/stdc++.h>
#define  na
#define ll long long
#define  ff first
#define ss second
#define vi vector<int>
#define vl vector<ll>
#define vll vector<pair<ll,ll> >
#define vvi vector<vector<int> >
#define vii vector<pair<int,int> >
#define pb push_back
#define inf 1000000000000000001
#define ninf -1000000007
#define mod 998244353
#define f(i,a,b) for(i=a;i<b;i++)
#define re0 return 0
using namespace std;

bool cmp(pair<pair<int,int>,int > &a,pair<pair<int,int>,int > &b)
{
      if(a.ff.ff==b.ff.ff)return a.ff.ss<b.ff.ss;
      return a.ff.ff<b.ff.ff;
}

ll nck(ll n,ll k)
{
	int i;
	ll sm=1;
	for(i=1;i<=k&&n;i++)sm*=n,n--,sm%=mod;
	for(i=1;i<=k;i++)sm/=i;
	return sm;
}
ll exp(ll j,ll n)
{
	ll i=n,res=1;

	while(j>0)
	{
		if(j&1)res*=i;
		res%=mod;
		 i=i*i;
		 i%=mod;
		j>>=1;
	}

	return res%mod;
}

int main()
{
	#ifdef ha
	freopen("input.txt","r",stdin);
	freopen("output.txt","w",stdout);
	#endif

  int T=1;

  //cin>>T;

  while(T--)
  {
  	int n,m,i,j;

  	cin>>n>>m;

  	int a[n][m+2];

  	f(i,0,n)
  	{  string s;
  	   cin>>s;
  		f(j,0,m+2)a[i][j]=s[j]-'0';
	}
	int b[n][2];

	for(i=n-1;i>-1;i--)
	{    int l=m+1,r=0;
		for(j=m+1;j>-1;j--)
		{
			if(a[i][j])break;
		}
		if(j>-1)r=j;
		for(j=0;j<m+2;j++)
		{
			if(a[i][j])break;
		}
		if(j<m+2)l=j;
		b[n-1-i][0]=m+1-l;
		b[n-1-i][1]=r;
	}
	int l[n],r[n];
	l[0]=2*b[0][1],r[0]=m+1;
	for(i=1;i<n-1;i++)
	{
		int p=2*b[i][1]+1,q=m+2;
		l[i]=min(p+l[i-1],r[i-1]+q);

		p=2*b[i][0]+1,q=m+2;
		r[i]=min(r[i-1]+p,l[i-1]+q);
	}
	int ansl,ansr;

	if(n>1)ansl=l[n-2]+b[n-1][1]+1,ansr=r[n-2]+b[n-1][0]+1;
	else ansl=b[0][1],ansr=b[0][0];

    cout<<min(ansl,ansr);
  }

 }


#include <bits/stdc++.h>
#define  na
#define ll long long
#define  ff first
#define ss second
#define vi vector<int>
#define vl vector<ll>
#define vll vector<pair<ll,ll> >
#define vvi vector<vector<int> >
#define vii vector<pair<int,int> >
#define pb push_back
#define inf 1000000000000000001
#define ninf -1000000007
#define mod 998244353
#define f(i,a,b) for(i=a;i<b;i++)
#define re0 return 0
using namespace std;

bool cmp(pair<pair<int,int>,int > &a,pair<pair<int,int>,int > &b)
{
      if(a.ff.ff==b.ff.ff)return a.ff.ss<b.ff.ss;
      return a.ff.ff<b.ff.ff;
}

ll nck(ll n,ll k)
{
	int i;
	ll sm=1;
	for(i=1;i<=k&&n;i++)sm*=n,n--,sm%=mod;
	for(i=1;i<=k;i++)sm/=i;
	return sm;
}
ll exp(ll j,ll n)
{
	ll i=n,res=1;

	while(j>0)
	{
		if(j&1)res*=i;
		res%=mod;
		 i=i*i;
		 i%=mod;
		j>>=1;
	}

	return res%mod;
}

int main()
{
	#ifdef ha
	freopen("input.txt","r",stdin);
	freopen("output.txt","w",stdout);
	#endif

  int T=1;

  //cin>>T;

  while(T--)
  {
  	int n,m,i,j;

  	cin>>n>>m;

  	int a[n][m+2];

  	f(i,0,n)
  	{  string s;
  	   cin>>s;
  		f(j,0,m+2)a[i][j]=s[j]-'0';
	}
	int b[n][2];

	for(i=n-1;i>-1;i--)
	{    int l=m+1,r=0;
		for(j=m+1;j>-1;j--)
		{
			if(a[i][j])break;
		}
		if(j>-1)r=j;
		for(j=0;j<m+2;j++)
		{
			if(a[i][j])break;
		}
		if(j<m+2)l=j;
		b[n-1-i][0]=m+1-l;
		b[n-1-i][1]=r;
	}
	int l[n],r[n];
	l[0]=2*b[0][1],r[0]=m+1;
	for(i=n-1;i>0;i--)
	{
		if(b[i][1])break;
	}
	int k=i;
	for(i=1;i<k;i++)
	{
		int p=2*b[i][1]+1,q=m+2;
		l[i]=min(p+l[i-1],r[i-1]+q);

		p=2*b[i][0]+1,q=m+2;
		r[i]=min(r[i-1]+p,l[i-1]+q);
	}
	int ansl,ansr;
	if(k)ansl=l[k-1]+b[k][1]+1,ansr=r[k-1]+b[k][0]+1;
	else ansl=b[0][1],ansr=ansl;
	cout<<min(ansl,ansr);

  }

 }


#include <bits/stdc++.h>
#define  na
#define ll long long
#define  ff first
#define ss second
#define vi vector<int>
#define vl vector<ll>
#define vll vector<pair<ll,ll> >
#define vvi vector<vector<int> >
#define vii vector<pair<int,int> >
#define pb push_back
#define inf 1000000000000000001
#define ninf -1000000007
#define mod 998244353
#define f(i,a,b) for(i=a;i<b;i++)
#define re0 return 0
using namespace std;

bool cmp(pair<pair<int,int>,int > &a,pair<pair<int,int>,int > &b)
{
      if(a.ff.ff==b.ff.ff)return a.ff.ss<b.ff.ss;
      return a.ff.ff<b.ff.ff;
}

ll nck(ll n,ll k)
{
	int i;
	ll sm=1;
	for(i=1;i<=k&&n;i++)sm*=n,n--,sm%=mod;
	for(i=1;i<=k;i++)sm/=i;
	return sm;
}
ll exp(ll j,ll n)
{
	ll i=n,res=1;

	while(j>0)
	{
		if(j&1)res*=i;
		res%=mod;
		 i=i*i;
		 i%=mod;
		j>>=1;
	}

	return res%mod;
}

int main()
{
	#ifdef ha
	freopen("input.txt","r",stdin);
	freopen("output.txt","w",stdout);
	#endif

  int T=1;

  //cin>>T;

  while(T--)
  {
  	int n,m,i,j;

  	cin>>n>>m;

  	int a[n][m+2];

  	f(i,0,n)
  	{  string s;
  	   cin>>s;
  		f(j,0,m+2)a[i][j]=s[j]-'0';
	}
	int b[n][2];

	for(i=n-1;i>-1;i--)
	{    int l=0,r=0;
		for(j=m+1;j>-1;j--)
		{
			if(a[i][j])break;
		}
		if(j>-1)r=j;
		for(j=0;j<m+2;j++)
		{
			if(a[i][j])break;
		}
		if(j<m+2)l=j;
		b[n-1-i][0]=m+1-l;
		b[n-1-i][1]=r;
	}
	int l[n],r[n];
	l[0]=2*b[0][1],r[0]=m+1;
	for(i=1;i<n-1;i++)
	{
		int p=2*b[i][1]+1,q=m+2;
		l[i]=min(p+l[i-1],r[i-1]+q);

		p=2*b[i][0]+1,q=m+2;
		r[i]=min(r[i-1]+p,l[i-1]+q);
	}
	int ansl,ansr;

	if(n>1)ansl=l[n-2]+b[n-1][1]+1,ansr=r[n-2]+b[n-1][0]+1;
	else ansl=b[0][1],ansr=b[0][0];

    cout<<min(ansl,ansr);
  }

 }


#include <bits/stdc++.h>
#define  na
#define ll long long
#define  ff first
#define ss second
#define vi vector<int>
#define vl vector<ll>
#define vll vector<pair<ll,ll> >
#define vvi vector<vector<int> >
#define vii vector<pair<int,int> >
#define pb push_back
#define inf 1000000000000000001
#define ninf -1000000007
#define mod 998244353
#define f(i,a,b) for(i=a;i<b;i++)
#define re0 return 0
using namespace std;

bool cmp(pair<pair<int,int>,int > &a,pair<pair<int,int>,int > &b)
{
      if(a.ff.ff==b.ff.ff)return a.ff.ss<b.ff.ss;
      return a.ff.ff<b.ff.ff;
}

ll nck(ll n,ll k)
{
	int i;
	ll sm=1;
	for(i=1;i<=k&&n;i++)sm*=n,n--,sm%=mod;
	for(i=1;i<=k;i++)sm/=i;
	return sm;
}
ll exp(ll j,ll n)
{
	ll i=n,res=1;

	while(j>0)
	{
		if(j&1)res*=i;
		res%=mod;
		 i=i*i;
		 i%=mod;
		j>>=1;
	}

	return res%mod;
}

int main()
{
	#ifdef ha
	freopen("input.txt","r",stdin);
	freopen("output.txt","w",stdout);
	#endif

  int T=1;

  //cin>>T;

  while(T--)
  {
  	int n,m,i,j;

  	cin>>n>>m;

  	int a[n][m+2];

  	f(i,0,n)
  	{  string s;
  	   cin>>s;
  		f(j,0,m+2)a[i][j]=s[j]-'0';
	}
	int b[n][2];

	for(i=n-1;i>-1;i--)
	{    int l=m+1,r=0;
		for(j=m+1;j>-1;j--)
		{
			if(a[i][j])break;
		}
		if(j>-1)r=j;
		for(j=0;j<m+2;j++)
		{
			if(a[i][j])break;
		}
		if(j<m+2)l=j;
		b[n-1-i][0]=m+1-l;
		b[n-1-i][1]=r;
	}
	int l[n],r[n];
	l[0]=2*b[0][1],r[0]=m+1;
	int k=0;
	for(i=1;i<n-1;i++)
	{   if(b[i][1]==0)k++;
	    else k=0;
		int p=2*b[i][1]+1,q=m+2;
		l[i]=min(p+l[i-1],r[i-1]+q);

		p=2*b[i][0]+1,q=m+2;
		r[i]=min(r[i-1]+p,l[i-1]+q);
	}
	int ansl,ansr;
	if(b[n-1][1]==0)k++;
	else k=0;
	if(n>1)ansl=l[n-2]+b[n-1][1]+1-k,ansr=r[n-2]+b[n-1][0]+1-k;
	else ansl=b[0][1],ansr=ansl;

    cout<<min(ansl,ansr);
  }

 }


#include "bits/stdc++.h"
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

#define sim template < class c
#define ris return * this
#define dor > debug & operator <<
#define eni(x) sim > typename \
enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifdef LOCAL
~debug() { cerr << endl; }
eni(!=) cerr << boolalpha << i; ris; }
eni(==) ris << range(begin(i), end(i)); }
sim, class b dor(pair < b, c > d) {
ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
*this << "[";
for (auto it = d.b; it != d.e; ++it)
*this << ", " + 2 * (it == d.b) << *it;
ris << "]";
}
#else
sim dor(const c&) { ris; }
#endif
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "
#define cool ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define int  long long int
#define pb push_back
#define fe first
#define lb lower_bound
#define ub upper_bound
#define pii pair<pair<int,int>,pair<int,int> >
#define se second
#define endl "\n"
#define pi pair<int, int>
#define mi          map<int,int>
#define mii         map<pi,int>
#define vi vector<int>
#define vvi vector<vi>
#define bs   binary_search
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rep1(i,a,b) for(int i=a;i<=b;i++)
#define all(c) (c).begin(),(c).end()
#define sz(x)       (int)x.size()
#define PI 3.14159265358979323846

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> o_set;

 const int N=2e5+10;

 const int INF=1e18;

 int mod= 1e9+7;
 int dx[4]={0,0,+1,-1};
 int dy[4]={+1,-1,0,0};

int po(int a, int b) {
	int res = 1;
	while (b > 0) {
		if (b & 1)
			res = (res%mod * a%mod) % mod;
		a =(a%mod*a%mod) % mod;
		b >>= 1;
	}
	 return res;
  }

int n,m,ans=1e18,idx;

void cal(int r,int c,vector<string >vs,int cost) {
	   if(r==idx) {
		     int lst=0;
		     if(c==0) {
				    for(int i=m-1;i>=0;i--) {
						    if(vs[r][i]=='1') {
								   lst=i;
								   break;
								}
						}
						cost+=lst;
					 }
			 else {
				    rep(i,0,m) {
						  if(vs[r][i]=='1') {
							     lst=i;
							    break;
							  }
						}
						cost+=m-1-lst;
				 }
				 ans=min(ans,cost);
				 return;
		   }

	   int ct=0,lst=0,sum=0;
	   if(c==0) {
		  for(int i=m-1;i>=0;i--) {
			     if(vs[r][i]=='1') {
					    lst=i;
					    break;
					}
			   }
			   cal(r-1,0,vs,cost+1+(lst==0?0:2*lst));
			   cal(r-1,m-1,vs,cost+m);

	   }
	  else {
		      rep(i,0,m) {
				   if(vs[r][i]=='1') {
					   lst=i;
					   break;
				   }
				}

			  cal(r-1,0,vs,cost+m);
			  cal(r-1,m-1,vs,cost+1+(lst==0?0:2*(m-1-lst)));
		  }
	}

void solve() {
    cin>>n>>m;
    m+=2;
    vector<string > vs(n);

    int nx=0;

    rep(i,0,n) {
		cin>>vs[i];
		int yan=0;
		rep(j,0,sz(vs[i])) {
			  if(vs[i][j]=='1') {
				  yan=1;
				  nx=1;
			  }
			}
		if(nx==0)  {
			idx=i+1;

		}
	}

    //~ cout<<idx<<endl;
    if(idx==n) {
		   cout<<0<<endl;
		   return;
		}

   cal(n-1,0,vs,0);
   cout<<ans<<endl;
}

int32_t main() {
	cool;
	int t=1;
	//~ freopen("input.txt","r",s	tdin);
    //~ freopen("output.txt","w",stdout);

    //~ cin>>t;
	while(t--)
	  solve();

  return 0;
}


#include "bits/stdc++.h"
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

#define sim template < class c
#define ris return * this
#define dor > debug & operator <<
#define eni(x) sim > typename \
enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifdef LOCAL
~debug() { cerr << endl; }
eni(!=) cerr << boolalpha << i; ris; }
eni(==) ris << range(begin(i), end(i)); }
sim, class b dor(pair < b, c > d) {
ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
*this << "[";
for (auto it = d.b; it != d.e; ++it)
*this << ", " + 2 * (it == d.b) << *it;
ris << "]";
}
#else
sim dor(const c&) { ris; }
#endif
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "
#define cool ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define int  long long int
#define pb push_back
#define fe first
#define lb lower_bound
#define ub upper_bound
#define pii pair<pair<int,int>,pair<int,int> >
#define se second
#define endl "\n"
#define pi pair<int, int>
#define mi          map<int,int>
#define mii         map<pi,int>
#define vi vector<int>
#define vvi vector<vi>
#define bs   binary_search
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rep1(i,a,b) for(int i=a;i<=b;i++)
#define all(c) (c).begin(),(c).end()
#define sz(x)       (int)x.size()
#define PI 3.14159265358979323846

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> o_set;

 const int N=2e5+10;

 const int INF=1e18;

 int mod= 1e9+7;
 int dx[4]={0,0,+1,-1};
 int dy[4]={+1,-1,0,0};

int po(int a, int b) {
	int res = 1;
	while (b > 0) {
		if (b & 1)
			res = (res%mod * a%mod) % mod;
		a =(a%mod*a%mod) % mod;
		b >>= 1;
	}
	 return res;
  }

int n,m,ans=1e18,idx;

void cal(int r,int c,vector<string >vs,int cost) {
	   if(r==idx) {
		     int lst=0;
		     if(c==0) {
				    for(int i=m-1;i>=0;i--) {
						    if(vs[r][i]=='1') {
								   lst=i;
								   break;
								}
						}
						cost+=lst;
					 }
			 else {
				    rep(i,0,m) {
						  if(vs[r][i]=='1') {
							     lst=i;
							    break;
							  }
						}
						cost+=m-1-lst;
				 }
				 ans=min(ans,cost);
				 return;
		   }

	   int ct=0,lst=0,sum=0;
	   if(c==0) {
		  for(int i=m-1;i>=0;i--) {
			     if(vs[r][i]=='1') {
					    lst=i;
					    break;
					}
			   }
			   cal(r-1,0,vs,cost+2*lst+1LL);
			   cal(r-1,m-1,vs,cost+m);

	   }
	  else {
		      rep(i,0,m) {
				   if(vs[r][i]=='1') {
					   lst=i;
					   break;
				   }
				}

			  cal(r-1,0,vs,cost+m);
			  cal(r-1,m-1,vs,cost+2*(m-1-lst)+1);
		  }
	}

void solve() {
    cin>>n>>m;
    m+=2;
    vector<string > vs(n);

    int nx=0;

    rep(i,0,n) {
		cin>>vs[i];
		int yan=0;
		rep(j,0,sz(vs[i])) {
			  if(vs[i][j]=='1') {
				  yan=1;
				  nx=1;
			  }
			}
		if(nx==0)  {
			idx=i+1;

		}
	}

    //~ cout<<idx<<endl;
    if(idx==n) {
		   cout<<0<<endl;
		   return;
		}

   cal(n-1,0,vs,0);
   cout<<ans<<endl;
}

int32_t main() {
	cool;
	int t=1;
	//~ freopen("input.txt","r",s	tdin);
    //~ freopen("output.txt","w",stdout);

    //~ cin>>t;
	while(t--)
	  solve();

  return 0;
}


#include "bits/stdc++.h"
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

#define sim template < class c
#define ris return * this
#define dor > debug & operator <<
#define eni(x) sim > typename \
enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifdef LOCAL
~debug() { cerr << endl; }
eni(!=) cerr << boolalpha << i; ris; }
eni(==) ris << range(begin(i), end(i)); }
sim, class b dor(pair < b, c > d) {
ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
*this << "[";
for (auto it = d.b; it != d.e; ++it)
*this << ", " + 2 * (it == d.b) << *it;
ris << "]";
}
#else
sim dor(const c&) { ris; }
#endif
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "
#define cool ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define int  long long int
#define pb push_back
#define fe first
#define lb lower_bound
#define ub upper_bound
#define pii pair<pair<int,int>,pair<int,int> >
#define se second
#define endl "\n"
#define pi pair<int, int>
#define mi          map<int,int>
#define mii         map<pi,int>
#define vi vector<int>
#define vvi vector<vi>
#define bs   binary_search
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rep1(i,a,b) for(int i=a;i<=b;i++)
#define all(c) (c).begin(),(c).end()
#define sz(x)       (int)x.size()
#define PI 3.14159265358979323846

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> o_set;

 const int N=2e5+10;

 const int INF=1e18;

 int mod= 1e9+7;
 int dx[4]={0,0,+1,-1};
 int dy[4]={+1,-1,0,0};

int po(int a, int b) {
	int res = 1;
	while (b > 0) {
		if (b & 1)
			res = (res%mod * a%mod) % mod;
		a =(a%mod*a%mod) % mod;
		b >>= 1;
	}
	 return res;
  }

int n,m,ans=1e18,idx;

void cal(int r,int c,vector<string >vs,int cost) {
	   if(r==idx) {
		     int lst=0;
		     if(c==0) {
				    for(int i=m-1;i>=0;i--) {
						    if(vs[r][i]=='1') {
								   lst=i;
								   break;
								}
						}
						cost+=lst;
					 }
			 else {
				    rep(i,0,m) {
						  if(vs[r][i]=='1') {
							     lst=i;
							    break;
							  }
						}
						cost+=m-1-lst;
				 }
				 ans=min(ans,cost);
				 return;
		   }

	   int ct=0,lst=0,sum=0;
	   if(c==0) {
		  for(int i=m-1;i>=0;i--) {
			     if(vs[r][i]=='1') {
					    lst=i;
					    break;
					}
			   }
			   cal(r-1,0,vs,cost+2*lst+1LL);
			   cal(r-1,m-1,vs,cost+m);

	   }
	  else {
		      rep(i,0,m) {
				   if(vs[r][i]=='1') {
					   lst=i;
					   break;
				   }
				}

			  cal(r-1,0,vs,cost+m);
			  cal(r-1,m-1,vs,cost+2*(m-1-lst)+1);
		  }
	}

void solve() {
    cin>>n>>m;
    m+=2;
    vector<string > vs(n);

    int nx=0;
    rep(i,0,n) {
		cin>>vs[i];
		int yan=0;
		rep(j,0,sz(vs[i])) {
			  if(vs[i][j]=='1') yan=1;
			}
		if(yan==0)  {
			idx=i+1;
			nx=1;
		}
	}

    if(idx==n) {
		   cout<<0<<endl;
		   return;
		}

   cal(n-1,0,vs,0);
   cout<<ans<<endl;
}

int32_t main() {
	cool;
	int t=1;
	//~ freopen("input.txt","r",s	tdin);
    //~ freopen("output.txt","w",stdout);

    //~ cin>>t;
	while(t--)
	  solve();

  return 0;
}


#include "bits/stdc++.h"
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

#define sim template < class c
#define ris return * this
#define dor > debug & operator <<
#define eni(x) sim > typename \
enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifdef LOCAL
~debug() { cerr << endl; }
eni(!=) cerr << boolalpha << i; ris; }
eni(==) ris << range(begin(i), end(i)); }
sim, class b dor(pair < b, c > d) {
ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
*this << "[";
for (auto it = d.b; it != d.e; ++it)
*this << ", " + 2 * (it == d.b) << *it;
ris << "]";
}
#else
sim dor(const c&) { ris; }
#endif
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "
#define cool ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define int  long long int
#define pb push_back
#define fe first
#define lb lower_bound
#define ub upper_bound
#define pii pair<pair<int,int>,pair<int,int> >
#define se second
#define endl "\n"
#define pi pair<int, int>
#define mi          map<int,int>
#define mii         map<pi,int>
#define vi vector<int>
#define vvi vector<vi>
#define bs   binary_search
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rep1(i,a,b) for(int i=a;i<=b;i++)
#define all(c) (c).begin(),(c).end()
#define sz(x)       (int)x.size()
#define PI 3.14159265358979323846

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> o_set;

 const int N=2e5+10;

 const int INF=1e18;

 int mod= 1e9+7;
 int dx[4]={0,0,+1,-1};
 int dy[4]={+1,-1,0,0};

int po(int a, int b) {
	int res = 1;
	while (b > 0) {
		if (b & 1)
			res = (res%mod * a%mod) % mod;
		a =(a%mod*a%mod) % mod;
		b >>= 1;
	}
	 return res;
  }

int n,m,ans=1e18,idx;

void cal(int r,int c,vector<string >vs,int cost) {
	   if(r==idx) {
		     int lst=0;
		     if(c==0) {
				    for(int i=m-1;i>=0;i--) {
						    if(vs[r][i]=='1') {
								   lst=i;
								   break;
								}
						}
						cost+=lst;
					 }
			 else {
				    rep(i,0,m) {
						  if(vs[r][i]=='1') {
							     lst=i;
							    break;
							  }
						}
						cost+=m-1-lst;
				 }
				 ans=min(ans,cost);
				 return;
		   }

	   int ct=0,lst=0,sum=0;
	   if(c==0) {
		  for(int i=m-1;i>=0;i--) {
			     if(vs[r][i]=='1') {
					    lst=i;
					    break;
					}
			   }
			   cal(r-1,0,vs,cost+2*lst+1LL);
			   cal(r-1,m-1,vs,cost+m);

	   }
	  else {
		      rep(i,0,m) {
				   if(vs[r][i]=='1') {
					   lst=i;
					   break;
				   }
				}

			  cal(r-1,0,vs,cost+m);
			  cal(r-1,m-1,vs,cost+2*(m-1-lst)+1);
		  }
	}

void solve() {
    cin>>n>>m;
    m+=2;
    vector<string > vs(n);

    int nx=0;
    rep(i,0,n) {
		cin>>vs[i];
		int yan=0;
		rep(j,0,sz(vs[i])) {
			  if(vs[i][j]=='1') yan=1;
			}
		if(yan==0 && nx==0) {
			idx=i;
			nx=1;
		}
	}

    if(idx+1==n) {
		   cout<<0<<endl;
		   return;
		}

   cal(n-1,0,vs,0);
   cout<<ans<<endl;
}

int32_t main() {
	cool;
	int t=1;
	//~ freopen("input.txt","r",s	tdin);
    //~ freopen("output.txt","w",stdout);

    //~ cin>>t;
	while(t--)
	  solve();

  return 0;
}


#include "bits/stdc++.h"
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

#define sim template < class c
#define ris return * this
#define dor > debug & operator <<
#define eni(x) sim > typename \
enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifdef LOCAL
~debug() { cerr << endl; }
eni(!=) cerr << boolalpha << i; ris; }
eni(==) ris << range(begin(i), end(i)); }
sim, class b dor(pair < b, c > d) {
ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
*this << "[";
for (auto it = d.b; it != d.e; ++it)
*this << ", " + 2 * (it == d.b) << *it;
ris << "]";
}
#else
sim dor(const c&) { ris; }
#endif
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "
#define cool ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define int  long long int
#define pb push_back
#define fe first
#define lb lower_bound
#define ub upper_bound
#define pii pair<pair<int,int>,pair<int,int> >
#define se second
#define endl "\n"
#define pi pair<int, int>
#define mi          map<int,int>
#define mii         map<pi,int>
#define vi vector<int>
#define vvi vector<vi>
#define bs   binary_search
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rep1(i,a,b) for(int i=a;i<=b;i++)
#define all(c) (c).begin(),(c).end()
#define sz(x)       (int)x.size()
#define PI 3.14159265358979323846

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> o_set;

 const int N=2e5+10;

 const int INF=1e18;

 int mod= 1e9+7;
 int dx[4]={0,0,+1,-1};
 int dy[4]={+1,-1,0,0};

int po(int a, int b) {
	int res = 1;
	while (b > 0) {
		if (b & 1)
			res = (res%mod * a%mod) % mod;
		a =(a%mod*a%mod) % mod;
		b >>= 1;
	}
	 return res;
  }

int n,m,ans=1e18,idx;

void cal(int r,int c,vector<string >vs,int cost) {
	   if(r==idx) {
		     int lst=0;
		     if(c==0) {
				    for(int i=m-1;i>=0;i--) {
						    if(vs[r][i]=='1') {
								   lst=i;
								   break;
								}
						}
						cost+=lst;
					 }
			 else {
				    rep(i,0,m) {
						  if(vs[r][i]=='1') {
							     lst=i;
							    break;
							  }
						}
						cost+=m-1-lst;
				 }
				 ans=min(ans,cost);
				 return;
		   }

	   int ct=0,lst=0,sum=0;
	   if(c==0) {
		  for(int i=m-1;i>=0;i--) {
			     if(vs[r][i]=='1') {
					    lst=i;
					    break;
					}
			   }
			   cal(r-1,0,vs,cost+2*lst+1LL);
			   cal(r-1,m-1,vs,cost+m);

	   }
	  else {
		      rep(i,0,m) {
				   if(vs[r][i]=='1') {
					   lst=i;
					   break;
				   }
				}

			  cal(r-1,0,vs,cost+m);
			  cal(r-1,m-1,vs,cost+2*(m-1-lst)+1);
		  }
	}

void solve() {
    cin>>n>>m;
    m+=2;
    vector<string > vs(n);

    int nx=0;

    rep(i,0,n) {
		cin>>vs[i];
		int yan=0;
		rep(j,0,sz(vs[i])) {
			  if(vs[i][j]=='1') {
				  yan=1;
				  nx=1;
			  }
			}
		if(nx==0)  {
			idx=i+1;
			nx=1;
		}
	}

    if(idx==n) {
		   cout<<0<<endl;
		   return;
		}

   cal(n-1,0,vs,0);
   cout<<ans<<endl;
}

int32_t main() {
	cool;
	int t=1;
	//~ freopen("input.txt","r",s	tdin);
    //~ freopen("output.txt","w",stdout);

    //~ cin>>t;
	while(t--)
	  solve();

  return 0;
}


#include "bits/stdc++.h"
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

#define sim template < class c
#define ris return * this
#define dor > debug & operator <<
#define eni(x) sim > typename \
enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifdef LOCAL
~debug() { cerr << endl; }
eni(!=) cerr << boolalpha << i; ris; }
eni(==) ris << range(begin(i), end(i)); }
sim, class b dor(pair < b, c > d) {
ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
*this << "[";
for (auto it = d.b; it != d.e; ++it)
*this << ", " + 2 * (it == d.b) << *it;
ris << "]";
}
#else
sim dor(const c&) { ris; }
#endif
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "
#define cool ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define int  long long int
#define pb push_back
#define fe first
#define lb lower_bound
#define ub upper_bound
#define pii pair<pair<int,int>,pair<int,int> >
#define se second
#define endl "\n"
#define pi pair<int, int>
#define mi          map<int,int>
#define mii         map<pi,int>
#define vi vector<int>
#define vvi vector<vi>
#define bs   binary_search
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rep1(i,a,b) for(int i=a;i<=b;i++)
#define all(c) (c).begin(),(c).end()
#define sz(x)       (int)x.size()
#define PI 3.14159265358979323846

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> o_set;

 const int N=2e5+10;

 const int INF=1e18;

 int mod= 1e9+7;
 int dx[4]={0,0,+1,-1};
 int dy[4]={+1,-1,0,0};

int po(int a, int b) {
	int res = 1;
	while (b > 0) {
		if (b & 1)
			res = (res%mod * a%mod) % mod;
		a =(a%mod*a%mod) % mod;
		b >>= 1;
	}
	 return res;
  }

int n,m,ans=1e18,idx;

void cal(int r,int c,vector<string >vs,int cost) {
	   if(r==idx) {
		     int lst=0;
		     if(c==0) {
				    for(int i=m-1;i>=0;i--) {
						    if(vs[r][i]=='1') {
								   lst=i;
								   break;
								}
						}
						cost+=lst;
					 }
			 else {
				    rep(i,0,m) {
						  if(vs[r][i]=='1') {
							     lst=i;
							    break;
							  }
						}
						cost+=m-1-lst;
				 }
				 ans=min(ans,cost);
				 return;
		   }

	   int ct=0,lst=0,sum=0;
	   if(c==0) {
		  for(int i=m-1;i>=0;i--) {
			     if(vs[r][i]=='1') {
					    lst=i;
					    break;
					}
			   }
			   cal(r-1,0,vs,cost+1+2*lst);
			   cal(r-1,m-1,vs,cost+m);

	   }
	  else {
		      lst=m-1;
		      rep(i,0,m) {
				   if(vs[r][i]=='1') {
					   lst=i;
					   break;
				   }
				}

			  cal(r-1,0,vs,cost+m);
			  cal(r-1,m-1,vs,cost+1+2*(m-1-lst));
		  }
	}

void solve() {
    cin>>n>>m;
    m+=2;
    vector<string > vs(n);

    int nx=0;

    rep(i,0,n) {
		cin>>vs[i];
		int yan=0;
		rep(j,0,sz(vs[i])) {
			  if(vs[i][j]=='1') {
				  yan=1;
				  nx=1;
			  }
			}
		if(nx==0)  {
			idx=i+1;

		}
	}

    //~ cout<<idx<<endl;
    if(idx==n) {
		   cout<<0<<endl;
		   return;
		}

   cal(n-1,0,vs,0);
   cout<<ans<<endl;
}

int32_t main() {
	cool;
	int t=1;
	//~ freopen("input.txt","r",s	tdin);
    //~ freopen("output.txt","w",stdout);

    //~ cin>>t;
	while(t--)
	  solve();

  return 0;
}


#include "bits/stdc++.h"
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

#define sim template < class c
#define ris return * this
#define dor > debug & operator <<
#define eni(x) sim > typename \
enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifdef LOCAL
~debug() { cerr << endl; }
eni(!=) cerr << boolalpha << i; ris; }
eni(==) ris << range(begin(i), end(i)); }
sim, class b dor(pair < b, c > d) {
ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
*this << "[";
for (auto it = d.b; it != d.e; ++it)
*this << ", " + 2 * (it == d.b) << *it;
ris << "]";
}
#else
sim dor(const c&) { ris; }
#endif
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "
#define cool ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define int  long long int
#define pb push_back
#define fe first
#define lb lower_bound
#define ub upper_bound
#define pii pair<pair<int,int>,pair<int,int> >
#define se second
#define endl "\n"
#define pi pair<int, int>
#define mi          map<int,int>
#define mii         map<pi,int>
#define vi vector<int>
#define vvi vector<vi>
#define bs   binary_search
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rep1(i,a,b) for(int i=a;i<=b;i++)
#define all(c) (c).begin(),(c).end()
#define sz(x)       (int)x.size()
#define PI 3.14159265358979323846

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> o_set;

 const int N=2e5+10;

 const int INF=1e18;

 int mod= 1e9+7;
 int dx[4]={0,0,+1,-1};
 int dy[4]={+1,-1,0,0};

int po(int a, int b) {
	int res = 1;
	while (b > 0) {
		if (b & 1)
			res = (res%mod * a%mod) % mod;
		a =(a%mod*a%mod) % mod;
		b >>= 1;
	}
	 return res;
  }

int n,m,ans=1e18,idx;

void cal(int r,int c,vector<string >vs,int cost) {
	   if(r==idx) {
		     int lst=0;
		     if(c==0) {
				    for(int i=m-1;i>=0;i--) {
						    if(vs[r][i]=='1') {
								   lst=i;
								   break;
								}
						}
						cost+=lst;
					 }
			 else {
				    rep(i,0,m) {
						  if(vs[r][i]=='1') {
							     lst=i;
							    break;
							  }
						}
						cost+=m-1-lst;
				 }
				 ans=min(ans,cost);
				 return;
		   }

	   int ct=0,lst=0,sum=0;
	   if(c==0) {
		  for(int i=m-1;i>=0;i--) {
			     if(vs[r][i]=='1') {
					    lst=i;
					    break;
					}
			   }
			   cal(r-1,0,vs,cost+2*lst+1LL);
			   cal(r-1,m-1,vs,cost+m);

	   }
	  else {
		      rep(i,0,m) {
				   if(vs[r][i]=='1') {
					   lst=i;
					   break;
				   }
				}

			  cal(r-1,0,vs,cost+m);
			  cal(r-1,m-1,vs,cost+2*(m-1-lst)+1);
		  }
	}

void solve() {
    cin>>n>>m;
    m+=2;
    vector<string > vs(n);

    int nx=0;
    rep(i,0,n) {
		cin>>vs[i];
		int yan=0;
		rep(j,0,sz(vs[i])) {
			  if(vs[i][j]=='1') yan=1;
			}
		if(yan==0 && nx==0) {
			idx=i+1;
			nx=1;
		}
	}

    if(idx==n) {
		   cout<<0<<endl;
		   return;
		}

   cal(n-1,0,vs,0);
   cout<<ans<<endl;
}

int32_t main() {
	cool;
	int t=1;
	//~ freopen("input.txt","r",s	tdin);
    //~ freopen("output.txt","w",stdout);

    //~ cin>>t;
	while(t--)
	  solve();

  return 0;
}


#include "bits/stdc++.h"
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

#define sim template < class c
#define ris return * this
#define dor > debug & operator <<
#define eni(x) sim > typename \
enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifdef LOCAL
~debug() { cerr << endl; }
eni(!=) cerr << boolalpha << i; ris; }
eni(==) ris << range(begin(i), end(i)); }
sim, class b dor(pair < b, c > d) {
ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
*this << "[";
for (auto it = d.b; it != d.e; ++it)
*this << ", " + 2 * (it == d.b) << *it;
ris << "]";
}
#else
sim dor(const c&) { ris; }
#endif
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "
#define cool ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define int  long long int
#define pb push_back
#define fe first
#define lb lower_bound
#define ub upper_bound
#define pii pair<pair<int,int>,pair<int,int> >
#define se second
#define endl "\n"
#define pi pair<int, int>
#define mi          map<int,int>
#define mii         map<pi,int>
#define vi vector<int>
#define vvi vector<vi>
#define bs   binary_search
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rep1(i,a,b) for(int i=a;i<=b;i++)
#define all(c) (c).begin(),(c).end()
#define sz(x)       (int)x.size()
#define PI 3.14159265358979323846

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> o_set;

 const int N=2e5+10;

 const int INF=1e18;

 int mod= 1e9+7;
 int dx[4]={0,0,+1,-1};
 int dy[4]={+1,-1,0,0};

int po(int a, int b) {
	int res = 1;
	while (b > 0) {
		if (b & 1)
			res = (res%mod * a%mod) % mod;
		a =(a%mod*a%mod) % mod;
		b >>= 1;
	}
	 return res;
  }

int n,m,ans=1e18,idx;

void cal(int r,int c,vector<string >vs,int cost) {
	   if(r==idx) {
		     int lst=0;
		     if(c==0) {
				    for(int i=m-1;i>=0;i--) {
						    if(vs[r][i]=='1') {
								   lst=i;
								   break;
								}
						}
						cost+=lst;
					 }
			 else {
				    rep(i,0,m) {
						  if(vs[r][i]=='1') {
							     lst=i;
							    break;
							  }
						}
						cost+=m-1-lst;
				 }
				 ans=min(ans,cost);
				 return;
		   }

	   int ct=0,lst=0,sum=0;
	   if(c==0) {
		  for(int i=m-1;i>=0;i--) {
			     if(vs[r][i]=='1') {
					    lst=i;
					    break;
					}
			   }
			   cal(r-1,0,vs,cost+2*lst+1LL);
			   cal(r-1,m-1,vs,cost+m);

	   }
	  else {
		      rep(i,0,m) {
				   if(vs[r][i]=='1') {
					   lst=i;
					   break;
				   }
				}

			  cal(r-1,0,vs,cost+m);
			  cal(r-1,m-1,vs,cost+1+(lst==0?0:2*(m-1-lst)));
		  }
	}

void solve() {
    cin>>n>>m;
    m+=2;
    vector<string > vs(n);

    int nx=0;

    rep(i,0,n) {
		cin>>vs[i];
		int yan=0;
		rep(j,0,sz(vs[i])) {
			  if(vs[i][j]=='1') {
				  yan=1;
				  nx=1;
			  }
			}
		if(nx==0)  {
			idx=i+1;

		}
	}

    //~ cout<<idx<<endl;
    if(idx==n) {
		   cout<<0<<endl;
		   return;
		}

   cal(n-1,0,vs,0);
   cout<<ans<<endl;
}

int32_t main() {
	cool;
	int t=1;
	//~ freopen("input.txt","r",s	tdin);
    //~ freopen("output.txt","w",stdout);

    //~ cin>>t;
	while(t--)
	  solve();

  return 0;
}