点击打开链接
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<cstring>
#include<string.h>
#include<math.h>
#include<algorithm>
#define inf 0x3f3f3f3f
#define LL long long
using namespace std;
const int maxn=1e3+5;
int T=0,N=0,M=0,xx=0,yy=0,p[maxn*maxn],sum=0,result=inf;
void init()
{
for(int i=0;i<=N*N+1;i++){
p[i]=-1;
}
}
int find(int x){
if(p[x]!=x){
return p[x]=find(p[x]);
}
else return x;
}
int main()
{
int xx=0,yy=0,temp1,temp2;
scanf("%d",&T);
while (T--) {
bool flag=false;
scanf("%d %d",&N,&M);
init();
for(int i=1;i<=M;i++){
scanf("%d %d",&xx, &yy);
if(!flag){
int loc=(xx-1)*N+yy;
p[loc]=loc;//必须要有的
//第一行 翻了就是标记0
if(loc<=N&&loc>0){
p[0]=0;
temp1=find(loc);
if(temp1!=0) p[temp1]=0;
}
else if(loc>N*(N-1)&&loc<=N*N){//最后一行 翻了就是标记N*N+1
p[N*N+1]=N*N+1;
temp1 = find(loc);
if(temp1!=N*N+1) p[temp1]=N*N+1;
}
//左
if(loc%N>1&&p[loc-1]!=-1){
temp1= find(loc);
temp2= find(loc-1);
if(temp1!=temp2) p[temp1] =temp2;
}
//上
if(loc/N>0&&p[loc-N]!=-1){
temp1= find(loc);
temp2= find(loc-N);
if(temp1!=temp2) p[temp1]=temp2;
}
//右
if(loc%N!=0&&p[loc+1]!=-1){
temp1=find(loc);
temp2=find(loc+1);
if(temp1!=temp2) p[temp1]=temp2;
}
//下
if(loc+N<=N*N&&p[loc+N]!=-1){
temp1=find(loc);
temp2=find(loc+N);
if(temp1!=temp2) p[temp1]=temp2;
}
// cout<< temp1<<" "<<p[temp1] << endl;
if(p[0]!=-1&&p[N*N+1]!=-1&&find(0)==find(N*N+1)){//一定要用find(0)==find(N*N+1)
flag=true;
printf("%d\n",i);
}
}
}
if(!flag){
printf("-1\n");
}
}
return 0;
}