Question

Programming language is Java 8

Thank you

Things are tense on the battlefield and our army is on the verge of defeat. The only chance is to retreat for now, regroup, aIf it is possible to reach from cell S to cell K, print the minimum number of moves required to do so. If not, print the word7 XxxxxX Sample Output 2 29 Sample Input 3 7 Sample Output 3 IMPOSSIBLEHINT The idea to is run a BFS from cell S in the table. To do this you need the following: An n x n boolean matrix that keeps

0 0
Add a comment Improve this question Transcribed image text
Answer #1

I have Solved the above problem in java, The solution works well for the above test cases. It is a basic use case of BFS algorithm. I have created a custom class called pair that stores the location of each point(co-ordinates) along with the distances travelled so far. I have also added relevant comments for you to understand.

SOLUTION:

import java.util.*;
import java.lang.*;
import java.io.*;
class Solution
{
   public static void main (String[] args) throws java.lang.Exception
   {
   Scanner sc = new Scanner(System.in);
       int n=sc.nextInt();
       char[][] ar= new char[n][n]; //input array
       boolean[][] visited=new boolean[n][n]; //visited array
       int pos_x=0,pos_y=0; //position of s
       int ans=-1;
       for(int i=0;i<n;i++){
       String s=sc.next(); //get next line
       for(int j=0;j<n;j++){
       ar[i][j]=s.charAt(j); //fill the array per character
       if(ar[i][j]=='S'){ //if character is Starting point
       pos_x=i; //initialize coordinates of S
       pos_y=j;
       }
       }
       }
       Queue<pair> q = new LinkedList<>(); //create queue
       q.add(new pair(pos_x,pos_y,0)); //add to queue
       while(!q.isEmpty()){
       pair p=q.remove(); //remove and make it visited true
       visited[p.x][p.y]=true;
       //System.out.println(p.x+" "+p.y+" "+p.ans);
       if(ar[p.x][p.y]=='K') { //if we have reached K(destination)
       ans=p.ans; //fetch the answer and break out
       break;
       }
       //Now adding all neighbours to the queue
       // check and move to (x-1,y)
       if(p.x-1>=0 && p.x-1<n && p.y>=0 && p.y<n && ar[p.x-1][p.y]!='X' && !visited[p.x-1][p.y])
       q.add(new pair(p.x-1,p.y,p.ans+1));
       // check and move to (x,y+1)
       if(p.x>=0 && p.x<n && p.y+1>=0 && p.y+1<n && ar[p.x][p.y+1]!='X' && !visited[p.x][p.y+1])
       q.add(new pair(p.x,p.y+1,p.ans+1));
       // check and move to (x+1,y)
       if(p.x+1>=0 && p.x+1<n && p.y>=0 && p.y<n && ar[p.x+1][p.y]!='X' && !visited[p.x+1][p.y])
       q.add(new pair(p.x+1,p.y,p.ans+1));
       // check and move to (x,y-1)
       if(p.x>=0 && p.x<n && p.y-1>=0 && p.y-1<n && ar[p.x][p.y-1]!='X' && !visited[p.x][p.y-1])
       q.add(new pair(p.x,p.y-1,p.ans+1));
       }
       //print the answer
       if(ans==-1)
       System.out.println("IMPOSSIBLE");
       else System.out.println(ans);
   }
//custom class pair that stores location of a the coordinates and the distance so far
public static class pair{
int x;
int y;
int ans;
pair(int a,int b,int answer){
x=a;y=b;ans=answer;
}
}
}

Add a comment
Know the answer?
Add Answer to:
Things are tense on the battlefield and our army is on the verge of defeat. The only chance is to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • You're given a chess board with dimension n x n. There's a king at the bottom...

    You're given a chess board with dimension n x n. There's a king at the bottom right square of the board marked with s. The king needs to reach the top left square marked with e. The rest of the squares are labeled either with an integer p (marking a point) or with x marking an obstacle. Note that the king can move up, left and up-left (diagonal) only. Find the maximum points the king can collect and the number...

  • Please write code in java You’re given a chess board with dimension n x n. There’s...

    Please write code in java You’re given a chess board with dimension n x n. There’s a king at the bottom right square of the board marked with s. The king needs to reach the top left square marked with e. The rest of the squares are labeled either with an integer p (marking a point) or with x marking an obstacle. Note that the king can move up, left and up-left (diagonal) only. Find the maximum points the king...

  • 3. You are in a rectangular maze organized in the form of M x N cells/locations....

    3. You are in a rectangular maze organized in the form of M x N cells/locations. You are starting at the upper left corner (grid location: (1, 1)) and you want to go to the lower right corner (grid location: (M, N)). From any location, you can move either to the right or to the bottom, or go diagonal. I.e., from (i,j) you can move to (i, j + 1) or (i + 1,j) or to (i+1, 3+1). Cost of...

  • #include <iostream> #include <queue> using namespace std; class Graph { public: Graph(int n); ~Graph(); void addEdge(int...

    #include <iostream> #include <queue> using namespace std; class Graph { public: Graph(int n); ~Graph(); void addEdge(int src, int tar); void BFTraversal(); void DFTraversal(); void printVertices(); void printEdges(); private: int vertexCount; int edgeCount; bool** adjMat; void BFS(int n, bool marked[]); void DFS(int n, bool marked[]); }; Graph::Graph(int n=0) { vertexCount = n; edgeCount = 0; if(n == 0) adjMat = 0; else { adjMat = new bool* [n]; for(int i=0; i < n; i++) adjMat[i] = new bool [n]; for(int i=0;...

  • In c programming The Consumer Submits processing requests to the producer by supplying a file name, its location and a character. It also outputs the contents of the file provided by the producer...

    In c programming The Consumer Submits processing requests to the producer by supplying a file name, its location and a character. It also outputs the contents of the file provided by the producer to the standard output. The Producer Accepts multiple consumer requests and processes each request by creating the following four threads. The reader thread will read an input file, one line at a time. It will pass each line of input to the character thread through a queue...

  • Please help run all the examples correctly and only the examples without extra things in or...

    Please help run all the examples correctly and only the examples without extra things in or less things in, it should run EXACTLY 100% like the examples. C language ONLY. And please dont reply if you cant run all the examples given. We know the tr command allows you to replace or translate characters in of a stream. It takes in two arguments - a set of characters to be replaced and a set of replacement characters. The full functionality...

  • Please use Python def findSubstrings(s):     # Write your code here Consider a string, s = "abc"....

    Please use Python def findSubstrings(s):     # Write your code here Consider a string, s = "abc". An alphabetically-ordered sequence of substrings of s would be {"a", "ab", "abc", "b", "bc", "c"}. If the sequence is reduced to only those substrings that start with a vowel and end with a consonant, the result is {"ab", "abc"}. The alphabetically first element in this reduced list is "ab", and the alphabetically last element is "abc". As a reminder: • Vowels: a, e, i,...

  • Programming project in Java: You are allowed to use the following methods from the Java API:...

    Programming project in Java: You are allowed to use the following methods from the Java API: class String length charAt class StringBuilder length charAt append toString class Character any method Create a class called HW2 that contains the following methods: 1. isAlphabeticalOrder takes a String as input and returns a boolean: The method returns true if all the letters of the input string are in alphabetical order, regardless of case. The method returns false otherwise. Do not use arrays to...

  • Drawing Characters C++ Problem Description Annie is trying to draw character lines that she would like...

    Drawing Characters C++ Problem Description Annie is trying to draw character lines that she would like to use as decorations in her text messages to her friends. She has a list of integer and character pairs that she uses as basis for drawing out the lines. Write a program that will help her accomplish the task more quickly. Input Format The input begins with an integer N indicating the number of integer and character pairs that follows. The succeeding lines...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT