Simple bfs solution c++


#1

int Solution::snakeLadder(vector<vector > &A, vector<vector > &B) {

  int n=10;
vector<vector<int>>board(10,vector<int>(10,-1));
for(int i=0;i<A.size();i++){
    int nextpos=A[i][0];
    int row=n - (nextpos+n-1)/n;
     int c = (nextpos-1)%n;           
                if(row%2 == n%2) {     
                    c = n-c-1; 
                }
                board[row][c]=A[i][1];
}
for(int i=0;i<B.size();i++){
    int nextpos=B[i][0];
    int row=n - (nextpos+n-1)/n;
     int c = (nextpos-1)%n;           
                if(row%2 == n%2) {     
                    c = n-c-1; 
                }
                board[row][c]=B[i][1];
    
}
vector<vector<bool>> visited(n , vector<bool>(n,false));
    
    queue<int> q;
    q.push(1);
    visited[n-1][0]=true;
    int steps=0;
    while(!q.empty())
    {
        int size=q.size();
        while(size--)  
        {
            int currpos = q.front();
            if(currpos==n*n)
                    return steps;
            q.pop(); 
            for(int i=1;i<=6;i++)   
            {
                int nextpos=currpos+i;
                if(nextpos>n*n)
                    break;
                int r = n - (nextpos+n-1)/n;   
                int c = (nextpos-1)%n;           
                if(r%2 == n%2)      
                    c = n-c-1; 
                if(!visited[r][c])
                {
                    visited[r][c]=true;
                    if(board[r][c]!=-1)
                        q.push(board[r][c]);  
                    else
                        q.push(nextpos);
                }
            }
        }
        steps++;
    }
    return -1;   

}