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

## Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →## Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →## Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →## Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →## Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →## Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →