Question
Find the Path Given an (m x n) matrix, write a program to traverse the cell and print the values present in the given path. Inclued necessary validation and proper error messages in case of given path is out of bounds. 5 x 5 matrix : {1 2 3 4 5 } (row 1) {6 7 8 9 0 } (row 2) {1 2 3 4 5 } (row 3) {6 7 8 9 0 } (row 4) {1 2 3 4 5 } (row 5) Path Notation : ‘’>” is going right, “v” going down, “<” is going left, “^” is going up
Answer
import java.util.Scanner;
class FindPath {
public static void main(String[] args) {
int row,col,startRow,startCol,length=0;
String path,output="";
Scanner scanner=new Scanner(System.in);
row=scanner.nextInt();
col=scanner.nextInt();
int matrix[][]=new int[row][col];
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
matrix[i][j]=scanner.nextInt();
}
}
startRow=scanner.nextInt();
startCol=scanner.nextInt();
scanner.nextLine();
path=scanner.nextLine();
if(row>startRow-1&&col>startCol-1)
{
startRow--;
startCol--;
output+=matrix[startRow][startCol]+" ";
for(length=0;length<path.length();length++)
{
if(path.charAt(length)=='>'&&startCol+1<col)
{
output+=matrix[startRow][startCol+1]+" ";
startCol++;
}
else if(path.charAt(length)=='<'&&startCol-1>=0)
{
output+=matrix[startRow][startCol-1]+" ";
startCol--;
}
else if(path.charAt(length)=='^'&&startRow-1>=0)
{
output+=matrix[startRow-1][startCol]+" ";
startRow--;
}
else if((path.charAt(length)=='v'||path.charAt(length)=='V')&&startRow+1<row)
{
output+=matrix[startRow+1][startCol]+" ";
startRow++;
}
else
{
System.out.println("Invalid path");
output="";
break;
}
}
}
else
{
System.out.println("Invalid path");
}
System.out.println(output);
}
}
No comments:
Post a Comment