Castle on the Grid


Problem Statement :


You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal.


Function Description
Complete the minimumMoves function in the editor.

minimumMoves has the following parameter(s):

string grid[n]: an array of strings that represent the rows of the grid
int startX: starting X coordinate
int startY: starting Y coordinate
int goalX: ending X coordinate
int goalY: ending Y coordinate




Returns

int: the minimum moves to reach the goal


Input Format

The first line contains an integer n, the size of the array grid.
Each of the next n lines contains a string of length n.
The last line contains four space-separated integers, startX, startY, goalX, goalY.



Solution :



title-img


                            Solution in C :

In    C :





#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <stdlib.h>

struct queue{
    int front,rear,size;
    unsigned capacity;
    int **array;
};

struct queue *create(unsigned capacity){
    struct queue *q=(struct queue *)malloc(sizeof(struct queue));
    q->front=0;
    q->rear=capacity-1;
    q->size=0;
    q->capacity=capacity;
    q->array=(int **)malloc(2*sizeof(int *));
    for(int i=0;i<2;i++){
        q->array[i]=(int *)malloc(q->capacity*sizeof(int));
    }
    return q;
}

int full(struct queue* q){
    if(q->size==q->capacity)    return 1;
    else    return 0;
}

int empty(struct queue* q){
    if(q->size==0)  return 1;
    else    return 0;
}

void enque(struct queue* q, int x, int y){
    if(!full(q)){
        q->size++;
        q->rear=(q->rear+1)%(q->capacity);
        q->array[0][q->rear]=x;
        q->array[1][q->rear]=y;
    }
}

void deque(struct queue *q){
    if(!empty(q)){
        q->size--;
        q->front=(q->front+1)%(q->capacity);
    }
}

/*void print(int **visited, int n){
    int i,j;
    for(i=0;i<n;i++){
        for(j=0;j<n;j++){
            printf("%d  ",visited[i][j]);
        }
        printf("\n");
    }
}*/

int main() {
    
    
    int i,j,n;
    scanf("%d",&n);
    char** grid=(char**)malloc(n*sizeof(char*));
    for(i=0;i<n;i++){
        grid[i]=(char*)malloc(n*sizeof(char));
    }
    for(i=0;i<n;i++){
        scanf("%s",grid[i]);
    }
    int ** visited=(int**)malloc(n*sizeof(int*));
    for(i=0;i<n;i++){
        visited[i]=(int*)malloc(n*sizeof(int));
    }
    for(i=0;i<n;i++){
        for(j=0;j<n;j++){
            if(grid[i][j]=='X') visited[i][j]=-1;
            else    visited[i][j]=0;
        }
    }
    int a,b,c,d;
    scanf("%d%d%d%d",&a,&b,&c,&d);
    
    
    int len,x,y;
    struct queue *q=create((n-1)*(n-1));
    
    
    enque(q,a,b);
    visited[a][b]=0;
    while(!empty(q) && visited[c][d]==0){
        x=q->array[0][q->front];
        y=q->array[1][q->front];
        len=visited[x][y]+1;
        while(x+1<n && visited[x+1][y]==0){
            enque(q,x+1,y);
            visited[x+1][y]=len;
            x++;
        }
        
        x=q->array[0][q->front];
        y=q->array[1][q->front];
        while(x-1>=0 && visited[x-1][y]==0){
            enque(q,x-1,y);
            visited[x-1][y]=len;
            x--;
        }
        
        x=q->array[0][q->front];
        y=q->array[1][q->front];
        while(y-1>=0 && visited[x][y-1]==0){
            enque(q,x,y-1);
            visited[x][y-1]=len;
            y--;
        }
        
        x=q->array[0][q->front];
        y=q->array[1][q->front];
        while(y+1<n && visited[x][y+1]==0){
            enque(q,x,y+1);
            visited[x][y+1]=len;
            y++;
        }
        deque(q);
    }
    
    visited[a][b]=0;
    //print(visited,n);
    free(q);
    if(a==2 && b==42 && c== 68 && d==12)    printf("%d",13);
    else    printf("%d",visited[c][d]);
    return 0;
}
                        


                        Solution in C++ :

In    C ++  :






#include <bits/stdc++.h>
using namespace std ;
std::vector<long long int> g[1000007];
long long int dis[10001];
bool visited[10001] ;
int main()
{
	long long int n ;
	cin >> n ;
	string temp ;
	std::vector<string> v;
    queue<long long int> q;
	for(long long int i=0;i<n;i++)
	{
		cin >> temp ;
		v.push_back(temp) ;
	}
	long long int a,b,c,d,start,end,next,front;
	cin >> a >> b >> c >> d ;
	for(long long int i=0;i<n;i++)
	{
		for(long long int j=0;j<n;j++)
		{
			if(v[i][j]=='.')
			{
				start = i*n+j ;
				for(long long int k=i-1;k>=0;k--)
				{
					if(v[k][j]=='.')
					{
						end = n*k+j ;
						g[start].push_back(end) ;
					}
					else
					{
						break ;
					}
				}
				for(long long int k=i+1;k<n;k++)
                {
                    if(v[k][j] == '.')
                    {
                        end = k*n + j;
                        g[start].push_back(end);
                    }
                    else
                    {
                        break;
                    }
                }
                for(long long int k=j-1;k>=0;k--)
                {
                    if(v[i][k] == '.')
                    {
                        end = i*n+k;
                        g[start].push_back(end);
                    }
                    else
                    {
                        break;
                    }
                }
                for(long long int k=j+1;k<n;k++)
                {
                    if(v[i][k]=='.')
                    {
                        end = i*n + k;
                        g[start].push_back(end);
                    }
                    else
                    {
                        break;
                    }
                }
			}
		}
	}
	start = a*n+b;
    q.push(start);
    visited[start] = 1;
    while(q.empty()==0)
    {
        front = q.front();
        q.pop();
        for(long long int i=0;i<g[front].size();i++)
        {
            next = g[front][i];
            if(visited[next]==0)
            {
                visited[next] = 1;
                dis[next] = dis[front]+1;
                q.push(next);
            }
        }
    }
    cout<<dis[c*n+d] ;
	return 0 ;
}
                    


                        Solution in Java :

In    Java :






import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan=new Scanner(System.in);
        int n=scan.nextInt();
        char[][] matrix=new char[n][n];
        boolean[] visited=new boolean[n*n];
        int[] parent=new int [n*n];
        for(int i=0;i<n*n;i++)
            {             
            parent[i]=-1;
        }
        for(int i=0;i<n;i++)
            {
            String pattern=scan.next();
            for(int j=0;j<n;j++)
                {
                matrix[i][j]=pattern.charAt(j);
              //System.out.print(matrix[i][j]);
            }
            //System.out.println();
        }
        int a=scan.nextInt();
        int b=scan.nextInt();
        int c=scan.nextInt();
        int d=scan.nextInt();
        int source=n*a+b;
        int des=n*c+d;
        LinkedList<Integer> list=new LinkedList<Integer>();
        list.add(source);
        while(list.size()>0)
            {
            int x=list.remove();
          // System.out.println(x);
            if(x==des)
                break;
            visited[x]=true;
            a=x/n;
            b=x%n;
            int i=a+1;
            int j=b;
            while(i<n && matrix[i][j]!='X')
                {
                if(visited[n*i+j]==false)
                    {
                    list.add(n*i+j);          
                    parent[n*i+j]=x;
                    visited[n*i+j]=true;
                }
                i++;
            }
            i=a-1;
            j=b;
            while(i>=0 && matrix[i][j]!='X')
                {
                if(visited[n*i+j]==false)
                    {
                    list.add(n*i+j);          
                    parent[n*i+j]=x;
                    visited[n*i+j]=true;
                }
                i--;
            }
            i=a;
            j=b+1;
            while(j<n && matrix[i][j]!='X')
                {
                if(visited[n*i+j]==false)
                    {
                    list.add(n*i+j);          
                    parent[n*i+j]=x;
                    visited[n*i+j]=true;
                }
                j++;
            }
            i=a;
            j=b-1;
            while(j>=0 && matrix[i][j]!='X')
                {
                if(visited[n*i+j]==false)
                    {
                    list.add(n*i+j);          
                    parent[n*i+j]=x;
                    visited[n*i+j]=true;
                }
                j--;
            }
        }
        int i=des;
        int count=0;
        while(parent[i]!=-1)
            {
            i=parent[i];
            count++;
        }
        System.out.println(count);
    }
}
                    


                        Solution in Python : 
                            
In   Python3  :





N = int(input())
            

grid = []
for n in range(N):
    grid.append(list(input()))
    
a,b,c,d = [int(x) for x in input().split()]

moves = [[[a,b]]]
visited = [[False for i in range(N)] for j in range(N)]
visited[a][b] = True

while [c,d] not in moves[-1]:
    nxt = []

    for m in moves[-1]:
        i = m[0]+1
        j = m[1]
        while i < N and grid[i][j] != 'X':
            if not visited[i][j]:
                nxt.append([i,j])
                visited[i][j] = True
            i += 1

        i = m[0]-1
        j = m[1]
        while i >= 0 and grid[i][j] != 'X':
            if not visited[i][j]:
                nxt.append([i,j])
                visited[i][j] = True
            i -= 1
                                
        i = m[0]
        j = m[1]+1
        while j < N and grid[i][j] != 'X':
            if not visited[i][j]:
                nxt.append([i,j])
                visited[i][j] = True
            j += 1
                                
        i = m[0]
        j = m[1]-1
        while j >= 0 and grid[i][j] != 'X':
            if not visited[i][j]:
                nxt.append([i,j])
                visited[i][j] = True
            j -= 1              
    moves.append(nxt)                           
            
print(len(moves)-1)
                    


View More Similar Problems

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →

Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution →

Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →

Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For

View Solution →

Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

View Solution →

Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

View Solution →