#include<bits/stdc++.h>
#define PB push_back
#define MP make_pair
#define F first
#define S second
#define loop(i,a,b) for(int i=a;i<b;i++)
#define si(n) scanf("%d",&n)
#define sll(n) scanf("%lld",&n)
using namespace std;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector< vi > vvi;
typedef vector< ii > vii;
//***********************************END OF TEMPLATE*********************************************************************
int a[502][502];
ii dp[502][502]; //dp[r][c].F => Min power to reach {r,c}
//dp[r][c].S => total power till {r,c} when optimal path followed
ii solve(int r,int c){
if(r<0||c<0)
return {1e7,1e7};
//base case
if(r==0&&c==0){
if(a[r][c] == 0)
return {1,1};
else if(a[r][c]>0)
return {0,a[r][c]};
else if(a[r][c]<0)
return {abs(a[0][0])+1,1};
}
if(dp[r][c].F!=-1)
return dp[r][c];
//Recursion
ii up = solve(r-1,c);
ii left = solve(r,c-1);
if(up.S+a[r][c]<=0){
up.F += abs(up.S+a[r][c])+1;
up.S += abs(up.S+a[r][c])+1;
}
if(left.S+a[r][c]<=0){
left.F += abs(left.S+a[r][c])+1;
left.S += abs(left.S+a[r][c])+1;
}
if(left.F<up.F)
dp[r][c] = {left.F,left.S+a[r][c]};
else if(up.F<left.F)
dp[r][c] = {up.F,up.S+a[r][c]};
else if(up.F==left.F)
dp[r][c] = {up.F,a[r][c]+max(up.S,left.S)};
return dp[r][c];
}
int main(){
int t;
int r,c;
si(t);
while(t--){
si(r);si(c);
loop(i,0,r){
loop(j,0,c){
si(a[i][j]);
dp[i][j].F=-1;
}
}
ii ans = solve(r-1,c-1);
/*loop(i,0,r){
loop(j,0,c){
printf("%d ",dp[i][j].F);
}
printf("\n");
}*/
printf("%d\n",ans.F);
}
return 0;
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KI2RlZmluZSBQQiBwdXNoX2JhY2sKI2RlZmluZSBNUCBtYWtlX3BhaXIKI2RlZmluZSBGIGZpcnN0CiNkZWZpbmUgUyBzZWNvbmQKI2RlZmluZSBsb29wKGksYSxiKSBmb3IoaW50IG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