You have a matrix of size **N** * **N** with rows numbered through 1 to **N** from top to bottom and columns through 1 to **N** from left to right. It contains all values from 1 to **N2**, i.e. each value from 1 to **N2** occurs exactly once in the matrix.

Now, you start from the cell containing value 1, and from there visit the cell with value 2, and then from there visit the cell with value 3, and so on till you have visited cell containing the number **N2**. In a single step, you can move from a cell to one of its adjacent cells. Two cells are said to be adjacent to each other if they share an edge between them.

Find out minimum number of steps required.

For example, if matrix is

1 3 2 4 You have a matrix of size **N** * **N** with rows numbered through 1 to **N** from top to bottom and columns through 1 to **N** from left to right. It contains all values from 1 to **N2**, i.e. each value from 1 to **N2** occurs exactly once in the matrix.

Now, you start from the cell containing value 1, and from there visit the cell with value 2, and then from there visit the cell with value 3, and so on till you have visited cell containing the number **N2**. In a single step, you can move from a cell to one of its adjacent cells. Two cells are said to be adjacent to each other if they share an edge between them.

Find out minimum number of steps required.

For example, if matrix is

1 3 2 4 You have a matrix of size **N** * **N** with rows numbered through 1 to **N** from top to bottom and columns through 1 to **N** from left to right. It contains all values from 1 to **N2**, i.e. each value from 1 to **N2** occurs exactly once in the matrix.

Now, you start from the cell containing value 1, and from there visit the cell with value 2, and then from there visit the cell with value 3, and so on till you have visited cell containing the number **N2**. In a single step, you can move from a cell to one of its adjacent cells. Two cells are said to be adjacent to each other if they share an edge between them.

Find out minimum number of steps required.

For example

2

1 3

2 4

3

1 7 9

2 4 8

3 6 5

int main() {

int t;

cin>>t;

while(tâ€“){

int n;

cin>>n;

int a[n][n];

map<int,int>row;

map<int ,int>col;

```
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)
{
cin>>a[i][j];
row[a[i][j]]=i;
col[a[i][j]]=j;
}
}
int sum=0;
for(int i=1;i<n*n;i++){
sum+=abs(row[i]-row[i+1]);
sum+=abs(col[i]-col[i+1]);
}
cout<<sum<<endl;
}
return 0;
```

}