April 2019

Connections

Solution

Implementation

#include<iostream>
#include<cstdlib>
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int A[256][2];
    memset(A,-1,sizeof(A[0][0])*256*2);
    int p,q,r,i,j,ans;
    char x[100];
    cin>>p>>q>>r;
    for(i=0;i<p;i++)
    {
        cin>>x;
        for(j=0;x[j]!='\0';j++)// store the each character and their location in the Array
        {    A[int(x[j])][0]=i;
            A[int(x[j])][1]=j;
        }    
    }
    for(i=0;i<r;i++)
    {
        cin>>x[0]>>x[1];
        if(A[x[0]][0]<0 || A[x[1]][0] < 0) //to check if the characters are present in the map.
        ans =-1;
        else ans = abs(A[x[0]][0]-A[x[1]][0])+abs(A[x[0]][1]-A[x[1]][1]);
        cout<<ans<<endl;
    }
}