Code Coach Solutions




2D Map[Pro]

Difficulty: Hard


Problem Statement:

You're given a representation of a 5x5 2D map, and if you can only move left, right, up, or down, determine how many moves you would have to make to get between two points on the map.

Task: 

Determine the total number of moves that are needed between two points on a map. The points that you move between are marked with a P and the spaces in between are marked with X.

Input Format: 

A string that represents the 2D space starting at the top left.  Each level from top to bottom is separated by a comma.

Output Format: 

An integer that represents the total number of moves that you had to make.

Sample Input: 

XPXXX,XXXXX,XXXXX,XXXPX,XXXXX

Sample Output: 

5

Explanation:

The map looks as:

XPXXX
XXXXX
XXXXX
XXXPX
XXXXX

You had to move right 2 spaces, then down 3 spaces for a total of 5 moves.

Solution:


s=input().split(",")
c,k,i1,j1,i2,j2=0,0,0,0,0,0
for i in range(len(s)):
    for j in range(len(s)):
        if(s[i][j]=='P'):
            c+=1
            k+=1
        if c==1 and k==1:
            i1,j1=i,j
            k=0
        if c==2 and k==1:
            i2,j2=i,j
            k=0
print(abs(i1-i2)+abs(j1-j2))


Explanation:

The main objective of this problem is to find the no of cross marks between two points. I come with a  simple logic is that, subtract the indexes of p1(i1, j1) , p2(i2, j2). To get the indexes, I have chosen increment variables c,k. Whenever c=1, k=1  then update the i1,j1 indexes. When c=2,k=1 then update i2, j2. Then apply abs() function for positive values.

Result:





Hope You understand the solution. The more you practice more you Learn. If there are any queries let us know in the comment section.

Tips to solve a problem in less time:

1. Don't read the whole problem statement initially. First, go through the input and output.

2. Mostly you will understand the problem while reading input, output, and Output explanation.

3. Now, Divide your Logic into 3 steps:

 step1: Input & output
                
                check whether you have written the correct syntax for input. To check you have to print the input.


    step2: Build your own logic with proper indentation.


    step3: Print the expected output.



Thank you!