Count Luck


Problem Statement :


Ron and Hermione are deep in the Forbidden Forest collecting potion ingredients, and they've managed to lose their way. The path out of the forest is blocked, so they must make their way to a portkey that will transport them back to Hogwarts.

Consider the forest as an  grid. Each cell is either empty (represented by .) or blocked by a tree (represented by ). Ron and Hermione can move (together inside a single cell) LEFT, RIGHT, UP, and DOWN through empty cells, but they cannot travel through a tree cell. Their starting cell is marked with the character , and the cell with the portkey is marked with a . The upper-left corner is indexed as .

.X.X......X
.X*.X.XXX.X
.XX.X.XM...
......XXXX.
In example above, Ron and Hermione are located at index  and the portkey is at . Each cell is indexed according to Matrix Conventions.

Hermione decides it's time to find the portkey and leave. They start along the path and each time they have to choose a direction, she waves her wand and it points to the correct direction. Ron is betting that she will have to wave her wand exactly  times. Can you determine if Ron's guesses are correct?

The map from above has been redrawn with the path indicated as a series where  is the starting point (no decision in this case),  indicates a decision point and  is just a step on the path:

.X.X.10000X
.X*0X0XXX0X
.XX0X0XM01.
...100XXXX.
There are three instances marked with  where Hermione must use her wand.

Note: It is guaranteed that there is only one path from the starting location to the portkey.

Function Description

Complete the countLuck function in the editor below. It should return a string, either  if Ron is correct or  if he is not.

countLuck has the following parameters:

matrix: a list of strings, each one represents a row of the matrix
k: an integer that represents Ron's guess
Input Format

The first line contains an integer , the number of test cases.

Each test case is described as follows:
The first line contains  space-separated integers  and , the number of forest matrix rows and columns.
Each of the next  lines contains a string of length  describing a row of the forest matrix.
The last line contains an integer , Ron's guess as to how many times Hermione will wave her wand.

Constraints

There will be exactly one  and one  in the forest.
Exactly one path exists between  and .
Output Format

On a new line for each test case, print  if Ron impresses Hermione by guessing correctly. Otherwise, print .Oops!.



Solution :



title-img


                            Solution in C :

In  C  :






#include <stdio.h>

#define MAX 1000000001

long long a[200][200], zas[1000000][2];
long long t,i,j,k,l,v,n,m,k,ki,kj,si,sj,zac,kon;
char c[1000];


long long sus(long long ii, long long jj)
{
long long vv=0;

if(ii>0 && a[ii-1][jj] !=-1) vv++;
if(jj>0 && a[ii][jj-1] !=-1) vv++;
if(ii+1<n && a[ii+1][jj] !=-1) vv++;
if(jj+1<m && a[ii][jj+1] !=-1) vv++;

if(ii == ki && jj == kj) return 0;

return vv;
}

int main()
{

scanf("%lld",&t);

while(t) {
  t--;
//  t=0;
  
  scanf("%lld %lld\n",&n,&m);
  
  for(i=0;i<n;i++) 
     {
      scanf("%s\n",c);
    for(j=0;j<m;j++) 
    {  
      if(c[j] == '.') a[i][j] = 1000000;
      if(c[j] == 'X') a[i][j] = -1;
      if(c[j] == 'M') {a[i][j] = MAX;si = i; sj = j;}
      if(c[j] == '*') {a[i][j] = 0;ki = i; kj = j;}
     }  
   }
   scanf("%lld",&k);

zac = 0;
kon = 1;

zas[0][0] = ki;
zas[0][1] = kj;

//printf("%lld %lld %lld\n",n,m,k);

while(a[si][sj] == MAX)
  {
   i = zas[zac][0];
   j = zas[zac][1];
  
   zac++;
  
   if(i>0 && a[i-1][j] != -1 && a[i][j]+1 < a[i-1][j])
      {
      a[i-1][j] = a[i][j] + 1;
      zas[kon][0] = i-1;
      zas[kon][1] = j;  
      kon++;
      } 
  if(j>0 && a[i][j-1] != -1 && a[i][j]+1 < a[i][j-1])
      {
      a[i][j-1] = a[i][j] + 1;
      zas[kon][0] = i;
      zas[kon][1] = j-1;  
      kon++;
      } 

   if(i+1<n && a[i+1][j] != -1 && a[i][j]+1 < a[i+1][j])
      {
      a[i+1][j] = a[i][j] + 1;
      zas[kon][0] = i+1;
      zas[kon][1] = j;  
      kon++;
      } 
   if(j+1<m && a[i][j+1] != -1 && a[i][j]+1 < a[i][j+1])
      {
      a[i][j+1] = a[i][j] + 1;
      zas[kon][0] = i;
      zas[kon][1] = j+1;  
      kon++;
      }  
  }

//printf("%lld\n",a[si][sj]);

i = si;
j = sj;
v = 0;

if(sus(i,j) > 1) v++;

while(i!= ki || j != kj)
 {
   if(i>0 && a[i-1][j]+1 == a[i][j])
     {
     i--;
     if(sus(i,j)>2) v++;
     continue;
     }
   if(j>0 && a[i][j-1]+1 == a[i][j])
     {
     j--;
     if(sus(i,j)>2) v++;
     continue;
     }
  if(i+1<n && a[i+1][j]+1 == a[i][j])
     {
     i++;
     if(sus(i,j)>2) v++;
     continue;
     }
  if(j+1<m && a[i][j+1]+1 == a[i][j])
     {
     j++;
     if(sus(i,j)>2) v++;
     continue;
     }  
 }

//printf("%lld=v\n",v);

if(v == k) 
  printf("Impressed\n",v);
else 
  printf("Oops!\n");  


}


return 0;
}
                        


                        Solution in C++ :

In  C++  :






#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <string>
#include <cstdio>
#include <vector>
#include <map>
#include <set>

using namespace std;

#define SIZE(A) (int((A).size()))
#define pb(A) push_back(A)
#define mp(A,B) make_pair(A,B)

const int fx[] = {0, 1, 0, -1}, fy[] = {1, 0, -1, 0};

int n, m;
int col;
int p[2000][2000];
char w[2000][2000];
char s[2000][2000];

void dfs(int x, int y) {
	w[x][y]=col;
	for (int i = 0; i < 4; i++) {
		int xx = x+fx[i], yy = y+fy[i];

		if (xx<0||yy<0||xx>=n||yy>=m||w[xx][yy]==col||s[xx][yy]=='X') continue;

		p[xx][yy] = (i+2)&3;
		dfs(xx, yy);
	}
}

int solve(int x, int y) {
	w[x][y] = ++col;
	for (int i = x, j = y; s[i][j]!='M';) {
		int v = p[i][j];
		i += fx[v]; j += fy[v];
		w[i][j] = col;
	}

	int amo=0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (w[i][j]==col) {
				if (s[i][j]=='*') continue;
				
				int add=0;

				for (int k = 0; k < 4; k++) {
					int xx = i+fx[k], yy=j+fy[k];
					if (xx<0||yy<0||xx>=n||yy>=m||w[xx][yy]==col||s[xx][yy]=='X') continue;
					add=1;
				}

				amo+=add;
			}
		}
	}
	return amo;
}

int main() {
	int t;
	cin >> t;
	for (; t--;) {
		cin >> n >> m;
		for (int i = 0; i < n; i++) {
			scanf("%s", s[i]);
		}
		int k;
		cin >> k;

		col++;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (s[i][j] == 'M') {
					dfs(i, j);
				}
			}
		}
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (s[i][j] == '*') {
					k -= solve(i, j);
				}
			}
		}
		puts(!k?"Impressed":"Oops!");
	}

    return 0;
}
                    


                        Solution in Java :

In  Java  :







import java.io.*;
import java.math.*;
import java.util.*;

import static java.util.Arrays.*;

public class Solution {
	private static final int mod = (int)1e9+7;

	final Random random = new Random(0);
	final IOFast io = new IOFast();

	/// MAIN CODE
	int w, h;
	char[][] cs;
	int[] dx = new int[] { 1, 0, -1, 0, };
	int[] dy = new int[] { 0, -1, 0, 1, };
	int dfs(int v, int p) {
		if(cs[v/w][v%w] == '*') return 0;
		int ret = -1;
		int move = 0;
		for(int i = 0; i < 4; i++) {
			final int y = v / w + dy[i];
			final int x = v % w + dx[i];
			if(x < 0 || y < 0 || x >= w || y >= h || cs[y][x] == 'X' || y*w+x == p) continue;
			move++;
			ret = Math.max(ret, dfs(y*w+x, v));
		}
		if(ret == -1) return -1;
		return ret + (move>1?1:0);
	}
	public void run() throws IOException {
		int TEST_CASE = Integer.parseInt(new String(io.nextLine()).trim());
//		int TEST_CASE = 1;
		while(TEST_CASE-- != 0) {
			h = io.nextInt();
			w = io.nextInt();
			cs = new char[h][];
			int cur = -1;
			for(int i = 0; i < h; i++) {
				cs[i] = io.next();
				for(int j = 0; j < w; j++) {
					if(cs[i][j] == 'M') cur = i*w+j;
				}
			}
			int K = io.nextInt();
			
			io.out.println(K == dfs(cur, -1) ? "Impressed" : "Oops!");
		}
	}
	

	/// TEMPLATE
	static int gcd(int n, int r) { return r == 0 ? n : gcd(r, n%r); }
	static long gcd(long n, long r) { return r == 0 ? n : gcd(r, n%r); }
	
	static <T> void swap(T[] x, int i, int j) {
		T t = x[i];
		x[i] = x[j];
		x[j] = t;
	}
	
	static void swap(int[] x, int i, int j) {
		int t = x[i];
		x[i] = x[j];
		x[j] = t;
	}
	

	static void radixSort(int[] xs) {
		int[] cnt = new int[(1<<16)+1];
		int[] ys = new int[xs.length];
		
		for(int j = 0; j <= 16; j += 16) {
			Arrays.fill(cnt, 0);
			for(int x : xs) { cnt[(x>>j&0xFFFF)+1]++; }
			for(int i = 1; i < cnt.length; i++) { cnt[i] += cnt[i-1]; }
			for(int x : xs) { ys[cnt[x>>j&0xFFFF]++] = x; }
			{ final int[] t = xs; xs = ys; ys = t; }
		}
	}
	
	static void radixSort(long[] xs) {
		int[] cnt = new int[(1<<16)+1];
		long[] ys = new long[xs.length];
		
		for(int j = 0; j <= 48; j += 16) {
			Arrays.fill(cnt, 0);
			for(long x : xs) { cnt[(int)(x>>j&0xFFFF)+1]++; }
			for(int i = 1; i < cnt.length; i++) { cnt[i] += cnt[i-1]; }
			for(long x : xs) { ys[cnt[(int)(x>>j&0xFFFF)]++] = x; }
			{ final long[] t = xs; xs = ys; ys = t; }
		}
	}
	

	static void arrayIntSort(int[][] x, int... keys) {
		Arrays.sort(x, new ArrayIntsComparator(keys));
	}
	
	static class ArrayIntsComparator implements Comparator<int[]> {
		final int[] KEY;
		
		public ArrayIntsComparator(int... key) {
			KEY = key;
		}
		
		@Override
		public int compare(int[] o1, int[] o2) {
			for(int k : KEY) if(o1[k] != o2[k]) return o1[k] - o2[k];
			return 0;
		}
	}
	
	static class ArrayIntComparator implements Comparator<int[]> {
		final int KEY;
		
		public ArrayIntComparator(int key) {
			KEY = key;
		}
		
		@Override
		public int compare(int[] o1, int[] o2) {
			return o1[KEY] - o2[KEY];
		}
	}
	
	
	void main() throws IOException {
		//		IOFast.setFileIO("rle-size.in", "rle-size.out");
		try {
			run();
		}
		catch (EndOfFileRuntimeException e) { }
		io.out.flush();
	}

	public static void main(String[] args) throws IOException {
		new Solution().main();
	}
	
	static class EndOfFileRuntimeException extends RuntimeException {
		private static final long serialVersionUID = -8565341110209207657L; }

	static
	public class IOFast {
		private BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		private PrintWriter out = new PrintWriter(System.out);

		void setFileIO(String ins, String outs) throws IOException {
			out.flush();
			out.close();
			in.close();
			in = new BufferedReader(new FileReader(ins));
			out = new PrintWriter(new FileWriter(outs));
			System.err.println("reading from " + ins);
		}

		//		private static final int BUFFER_SIZE = 50 * 200000;
		private static int pos, readLen;
		private static final char[] buffer = new char[1024 * 8];
		private static char[] str = new char[500*8*2];
		private static boolean[] isDigit = new boolean[256];
		private static boolean[] isSpace = new boolean[256];
		private static boolean[] isLineSep = new boolean[256];

		static {
			for(int i = 0; i < 10; i++) { isDigit['0' + i] = true; }
			isDigit['-'] = true;
			isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true;
			isLineSep['\r'] = isLineSep['\n'] = true;
		}

		public int read() throws IOException {
			if(pos >= readLen) {
				pos = 0;
				readLen = in.read(buffer);
				if(readLen <= 0) { throw new EndOfFileRuntimeException(); }
			}
			return buffer[pos++];
		}

		public int nextInt() throws IOException {
			return Integer.parseInt(nextString());
		}

		public long nextLong() throws IOException {
			return Long.parseLong(nextString());
		}

		public char nextChar() throws IOException {
			while(true) {
				final int c = read();
				if(!isSpace[c]) { return (char)c; }
			}
		}
		
		int reads(int len, boolean[] accept) throws IOException {
			try {
				while(true) {
					final int c = read();
					if(accept[c]) { break; }
					
					if(str.length == len) {
						char[] rep = new char[str.length * 3 / 2];
						System.arraycopy(str, 0, rep, 0, str.length);
						str = rep;
					}
					
					str[len++] = (char)c;
				}
			}
			catch(EndOfFileRuntimeException e) { ; }
			
			return len;
		}
		
		int reads(char[] cs, int len, boolean[] accept) throws IOException {
			try {
				while(true) {
					final int c = read();
					if(accept[c]) { break; }
					cs[len++] = (char)c;
				}
			}
			catch(EndOfFileRuntimeException e) { ; }
			
			return len;
		}

		public char[] nextLine() throws IOException {
			int len = 0;
			str[len++] = nextChar();
			len = reads(len, isLineSep);
			
			try {
				if(str[len-1] == '\r') { len--; read(); }
			}
			catch(EndOfFileRuntimeException e) { ; }
			
			return Arrays.copyOf(str, len);
		}

		public String nextString() throws IOException {
			return new String(next());
		}

		public char[] next() throws IOException {
			int len = 0;
			str[len++] = nextChar();
			len = reads(len, isSpace);
			return Arrays.copyOf(str, len);
		}

		public int next(char[] cs) throws IOException {
			int len = 0;
			cs[len++] = nextChar();
			len = reads(cs, len, isSpace);
			return len;
		}

		public double nextDouble() throws IOException {
			return Double.parseDouble(nextString());
		}

		public long[] nextLongArray(final int n) throws IOException {
			final long[] res = new long[n];
			for(int i = 0; i < n; i++) {
				res[i] = nextLong();
			}
			return res;
		}

		public int[] nextIntArray(final int n) throws IOException {
			final int[] res = new int[n];
			for(int i = 0; i < n; i++) {
				res[i] = nextInt();
			}
			return res;
		}

		public int[][] nextIntArray2D(final int n, final int k) throws IOException {
			final int[][] res = new int[n][];
			for(int i = 0; i < n; i++) {
				res[i] = nextIntArray(k);
			}
			return res;
		}

		public int[][] nextIntArray2DWithIndex(final int n, final int k) throws IOException {
			final int[][] res = new int[n][k+1];
			for(int i = 0; i < n; i++) {
				for(int j = 0; j < k; j++) {
					res[i][j] = nextInt();
				}
				res[i][k] = i;
			}
			return res;
		}

		public double[] nextDoubleArray(final int n) throws IOException {
			final double[] res = new double[n];
			for(int i = 0; i < n; i++) {
				res[i] = nextDouble();
			}
			return res;
		}

	}

}
                    


                        Solution in Python : 
                            
In   Python3  :









T = int(input()) # num test cases

def find(matrix, char):
    char_row = [row for row in range(len(matrix)) if char in matrix[row]][0]
    char_col = matrix[char_row].index(char)
    return char_row, char_col

def sum_coords(a, b):
    return a[0] + b[0], a[1] + b[1]

def find_path(matrix):
    N, M = len(matrix), len(matrix[0])
    start = find(matrix, 'M')
    end = find(matrix, '*')
    paths = [[start]]
    def get(coord):
        return matrix[coord[0]][coord[1]]
    while paths:
        new_paths = []
        for path in paths:
            for delta in (-1, 0), (1, 0), (0, -1), (0, 1):
                coord = sum_coords(path[-1], delta)
                if (0 <= coord[0] < N and 
                    0 <= coord[1] < M and
                    (len(path) == 1 or coord != path[-2]) and
                    get(coord) != 'X'
                   ):
                   	if coord == end:
                   	    return path + [coord]
                   	else:
                   	    new_paths.append(path + [coord])
        paths = new_paths
    return None

def count_waves(matrix, path):
    N, M = len(matrix), len(matrix[0])
    def get(coord):
        return matrix[coord[0]][coord[1]]
    count = 0
    for (i, path_coord) in enumerate(path[:-1]):
        neighbors = [sum_coords(path_coord, delta) for delta in [(-1, 0), (1, 0), (0, -1), (0, 1)]]
        options = [
			coord for coord in neighbors
        	if (0 <= coord[0] < N and 0 <= coord[1] < M and get(coord) != 'X')
        ]
        if len(options) > (2 if i>0 else 1):
            count += 1
    return count

for _i in range(T):
    # read matrix
    N, M = map(int, input().split())
    matrix = []
    for row in range(N):
        matrix.append(input())
    
    # read expected # waves
    K = int(input())
    
    # find path
    path = find_path(matrix)
    
    # count waves
    count = count_waves(matrix, path)
    
    # print answer
    print('Impressed' if K == count else 'Oops!')
                    


View More Similar Problems

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 →

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →