import java.util.LinkedList; import java.util.Scanner; import java.util.Vector; public class TsukubaD { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNext()) { int h = sc.nextInt(); int w = sc.nextInt(); if(h*h + w*w == 0) { break; } Guard[] guards = new Guard[h]; for(int k = 0; k < h; k++) { Vector vec = new Vector(); while(0==0) { int n = sc.nextInt(); if(n == 0) { break; } vec.add(n); } guards[k] = new Guard(vec); } GM gm = new GM(guards); gm.set(); for(int i = 0; i < w; i++) { gm.run(); } System.out.println("" + gm); } } } // Guard Manager class GM { public static final int ACTIVE = 1; public static final int CHARGE = 2; public static final int IDLE = 3; public LinkedList queue; Guard[] guards; public int ans; GM(Guard[] guards) { queue = new LinkedList(); this.guards = guards; this.ans = 0; } public void set() { for(int i = 0; i < guards.length; i++) { guards[i].setManager(this); } } public void run() { if(!queue.isEmpty() && queue.peek().getState() == IDLE) { queue.peek().setState(CHARGE); } for(int i = 0; i < guards.length; i++) { guards[i].run(); } } public String toString() { return ans + ""; } } class Guard { GM manager; Vector seq; int state, index, count; Guard(Vector vec) { this.seq = vec; this.state = GM.ACTIVE; this.index = 0; this.count = 0; } public void setManager(GM m) { this.manager = m; } public int getState() { return state; } public void setState(int state) { this.state = state; } public void run() { if(state == GM.ACTIVE) { if(++count == seq.elementAt(index)) { index = (index + 1) % seq.size(); if(manager.queue.isEmpty()) { manager.queue.add(this); state = GM.CHARGE; } else { manager.queue.add(this); state = GM.IDLE; } count = 0; } } else if(state == GM.CHARGE) { if(++count == seq.elementAt(index)) { index = (index + 1) % seq.size(); manager.queue.removeFirst(); state = GM.ACTIVE; count = 0; } } else if(state == GM.IDLE) { manager.ans += 1; } } }