Coin on the Table


Problem Statement :


You have a rectangular board consisting of n rows, numbered from 1 to n, and m columns, numbered from 1 to m. The top left is (1,1) and the bottom right is (n, m). Initially - at time  - there is a coin on the top-left cell of your board. Each cell of your board contains one of these letters:

*: Exactly one of your cells has letter '*'.

U: If at time t the coin is on cell (i, j) and cell (i, j) has letter 'U', the coin will be on cell (i-1, j) at time t+1, if i>1. Otherwise, there is no coin on your board at time t+1.

L: If at time t the coin is on cell (i, j) and cell (i, j) has letter 'L', the coin will be on cell (i, j-1) at time t+1, if j>1. Otherwise, there is no coin on your board at time t+1.

D: If at time t the coin is on cell (i, j) and cell (i, j) has letter 'D', the coin will be on cell (i+1,j) at time t+1, if i<N. Otherwise, there is no coin on your board at time t+1.

R: If at time t the coin is on cell (i, j) and cell (i, j) has letter 'R', the coin will be on cell (i,j+1) at time t+1, if j<M. Otherwise, there is no coin on your board at time t+1.

When the coin reaches a cell that has letter '*', it will stay there permanently. When you punch on your board, your timer starts and the coin moves between cells. Before starting the game, you can make operations to change the board, such that you are sure that at or before time k the coin will reach the cell having letter '*'. In each operation you can select a cell with some letter other than '*' and change the letter to 'U', 'L', 'R' or 'D'. You need to carry out as few operations as possible in order to achieve your goal. Your task is to find the minimum number of operations.

For example, given a grid of n=2 rows and m=3 columns:

UDL
RR*
the goal is to get from (1,1) to (2,3) in as few steps as possible. As the grid stands, it cannot be done because of the U in the cell at (1,1). If (1,1) is changed to D, the path (1,1) -> (2,1) -> (2,2) -> (2,3) is available. It could also be changed to R which would make the path (1,1) -> (1,2) -> (2,2) -> (2,3)  available. Either choice takes 1 change operation, which is the value sought if k >= 3. A lower value of -1 would result in a return value of  because the shortest path is 3 steps, starting from (1,1).

Function Description

Complete the coinOnTheTable function in the editor below. It should return an integer that represents the minimum operations to achieve the goal, or -1 if it is not possible.

coinOnTheTable has the following parameters:

m: an integer, the number of columns on the board
k: an integer, the maximum time to reach the goal
board: an array of strings where each string represents a row of the board
Input Format

The first line of input contains three integers, n, m, and k, the number of rows, the number of columns and the maximum time respectively.

The next n lines contain m letters each, describing your board.

Constraints

n,m <= 51
k <= 1000

Output Format

Print an integer which represents the minimum number of operations required to achieve your goal. If you cannot achieve your goal, print -1.



Solution :



title-img


                            Solution in C :

In C++ :





#include <cstdio>
#include <utility>
#include <map>
#include <queue>
using namespace std;

typedef pair<int,int> pii;
typedef pair<pii,int> ppp;

char board[55][55];
int N, M, K;
priority_queue<pair<int,ppp> > pq;
map<ppp,bool> seen;

bool inbound(int i, int j)
{
    return 0<=i && i<N && 0<=j && j<M;
}

int dijkstra()
{
    pq.push(make_pair(0, make_pair(pii(0,0),0)));
    while(!pq.empty()) {
        int dnow = -pq.top().first;
        pii pos = pq.top().second.first;
        int know = pq.top().second.second;
        pq.pop();
        if (board[pos.first][pos.second]=='*') return dnow;
        if (seen[make_pair(pos,know)]) continue;
        seen[make_pair(pos,know)]=true;
        int dx[] = {-1, 0, +1, 0};
        int dy[] = {0, +1, 0, -1};
        char dir[]="URDL";
        for(int z=0; z<4; ++z) {
            int i, j;
            i = pos.first+dx[z];
            j = pos.second+dy[z];
            if (!inbound(i,j)) continue;
            int extra;
            if (board[pos.first][pos.second]==dir[z]) extra=0;
            else extra=1;
            if (know<K) {
                pq.push(make_pair(-(dnow+extra), make_pair(pii(i,j),know+1)));
            }
        }
    }
    return -1;
}

int main()
{
    scanf("%d%d%d ", &N, &M, &K);
    for(int i=0; i<N; ++i) scanf("%s", board[i]);

    int ans = dijkstra();
    printf("%d\n", ans);
}








In Java :





import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

/**
 * @author Sergey Vorobyev (svorobyev@spb.com)
 */
public class Solution {

    Scanner in;
    PrintWriter out;

    public static void main(String[] args) throws Exception {
        Solution instance = new Solution();
        instance.go();
    }
    
    int ni() throws IOException {
        return in.nextInt();
    }

    String ns() throws IOException {
        return in.next();
    }

    private void go() throws Exception {
        in = new Scanner(System.in);
        out = new PrintWriter(System.out);

        int n= ni();
        int m= ni();
        int k= ni();

        int[][][] d = new int[k+1][n][m];
        char[][] a = new char[n][];
        for (int i=0; i<n; i++) {
            a[i] = ns().toCharArray();
        }

        for (int i=0; i<k+1; i++) {
            for (int j=0; j<n; j++) {
                Arrays.fill(d[i][j], Integer.MAX_VALUE / 3);
            }
        }
        d[0][0][0] = 0;

        final int[][] moves = new int[][] {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        final char[] symb = new char[] {'L', 'U', 'R', 'D'};

        for (int xod=1; xod<k+1; xod++) {
            for (int i=0; i<n; i++) {
                for (int j=0; j<m; j++) {

                    if (a[i][j] == '*') {
                        d[xod][i][j] =Math.min(d[xod][i][j], d[xod-1][i][j]);
                    }

                    for (int l=0; l<4; l++) {

                        int[] move = moves[l];

                        int x = i + move[0];
                        int y = j + move[1];
                        if (x >= 0 && x < n && y >= 0 && y < m) {
                            int newd = d[xod-1][x][y] + (symb[l] == a[x][y] ? 0 : 1);
                            if (newd < d[xod][i][j]) {
                                d[xod][i][j] = newd;
                            }
                        }

                    }

                }
            }
        }

        for (int i=0; i<n; i++) {
            for (int j=0; j<m; j++) {
                if (a[i][j] == '*') {
                    out.println(d[k][i][j] < Integer.MAX_VALUE / 3 ? d[k][i][j] : -1);
                }
            }
        }

        out.close();
    }
}








In C :





#include <stdio.h>

#define abs(x) ((x)<0?(-(x)):(x))

#define NMAX 50
#define KMAX 1000
#define BADVAL 1000000

char board[NMAX][NMAX];

int cache[KMAX+1][NMAX][NMAX];
#define CACHEMISS (-3)

// Problem parameters
int N, M, K;

// The end point
int endx, endy;

void flushcache(void)
{
    int i, j, k;

    for (k=0; k<=K; k++)
        for (j=0; j<N; j++)
            for (i=0; i<M; i++)
                cache[k][j][i] = CACHEMISS;
}


int solve(int x, int y, int k, int nchanges)
{
    char c;
    int km1;
    int iret, imin;

    if (cache[k][y][x]!=CACHEMISS)
        return nchanges + cache[k][y][x];

    // Have we reached the star?
    if (x==endx && y==endy)
        return nchanges;

    imin = BADVAL;
    if (k >= abs(x-endx)+abs(y-endy)) {
        km1 = k-1;
        c = board[y][x];
        if (x < M-1) {
            iret = solve(x+1, y,   km1, nchanges+(c != 'R'));
            if (iret < imin) imin=iret;
        }
        if (y < N-1) {
            iret = solve(x,   y+1, km1, nchanges+(c != 'D'));
            if (iret < imin) imin=iret;
        }
        if (x > 0) {
            iret = solve(x-1, y,   km1, nchanges+(c != 'L'));
            if (iret < imin) imin=iret;
        }
        if (y > 0) {
            iret = solve(x,   y-1, km1, nchanges+(c != 'U'));
            if (iret < imin) imin=iret;
        }
    }

    if (imin<BADVAL)
        cache[k][y][x] = imin - nchanges;

    return imin;
}

int main(void)
{
    int i, j;
    char linein[NMAX+1];
    int ires;

    // Read input
    scanf("%d %d %d", &N, &M, &K);

    for (j=0; j<N; j++) {
        scanf("%s", linein);
        for (i=0; i<M; i++) {
            board[j][i] = linein[i];
            if (linein[i]=='*') {
                endy = j;
                endx = i;
            }
        }
    }

    // Catch trivial solutions
    if ((endx+endy)==0) {
        //  - We are starting on the star
        ires = 0;
    } else if ((endx+endy) > K) {
        //  - We do not have enough moves to reach the star
        ires = -1;
    } else {
        // - Call the solver
        flushcache();
        ires = solve(0, 0, K, 0);
        if (ires == BADVAL) ires = -1;
    }

    printf("%d\n", ires);

    return 0;
}








In Python3 :





def main():
    height,width,k = [int(i) for i in input().split(" ")]
    k += 1
    board = [["" for j in range(width)] for i in range(height)]
    for i in range(height):
        row = input()
        for j in range(width):
            board[i][j] = row[j]
    a = [[set() for j in range(k+1)] for i in range(k+1)]
    a[0][0].add((0,0))
    for i in range(k):
        for j in range(k):
            #print([i,j])
            #for (y,x) in a[i][j]:
                #print (x,y)
            for (y,x) in a[i][j]:
                if board[y][x]=="*":
                    print(i)
                    return
                elif board[y][x]=="L":
                    if x-1>=0:
                        a[i][j+1].add((y,x-1))
                    if y-1>=0:
                        a[i+1][j+1].add((y-1,x))
                    if y+1<height:
                        a[i+1][j+1].add((y+1,x))
                    if x+1<width:
                        a[i+1][j+1].add((y,x+1))
                elif board[y][x]=="R":
                    if x-1>=0:
                        a[i+1][j+1].add((y,x-1))
                    if y-1>=0:
                        a[i+1][j+1].add((y-1,x))
                    if y+1<height:
                        a[i+1][j+1].add((y+1,x))
                    if x+1<width:
                        a[i][j+1].add((y,x+1))
                elif board[y][x]=="U":
                    if x-1>=0:
                        a[i+1][j+1].add((y,x-1))
                    if y-1>=0:
                        a[i][j+1].add((y-1,x))
                    if y+1<height:
                        a[i+1][j+1].add((y+1,x))
                    if x+1<width:
                        a[i+1][j+1].add((y,x+1))
                elif board[y][x]=="D":
                    if x-1>=0:
                        a[i+1][j+1].add((y,x-1))
                    if y-1>=0:
                        a[i+1][j+1].add((y-1,x))
                    if y+1<height:
                        a[i][j+1].add((y+1,x))
                    if x+1<width:
                        a[i+1][j+1].add((y,x+1))
    print(-1)

main()
                        








View More Similar Problems

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 →

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →