# 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 :

```                            ```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

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;

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;
}
}

cache[k][y][x] = imin - nchanges;

return imin;
}

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

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)]
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:
if y-1>=0:
if y+1<height:
if x+1<width:
elif board[y][x]=="R":
if x-1>=0:
if y-1>=0:
if y+1<height:
if x+1<width:
elif board[y][x]=="U":
if x-1>=0:
if y-1>=0:
if y+1<height:
if x+1<width:
elif board[y][x]=="D":
if x-1>=0:
if y-1>=0:
if y+1<height:
if x+1<width:
print(-1)

main()```
```

## Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

## Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

## Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

## Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

## No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

## Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor