• Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
Friday, January 27, 2023
  • Login
Zeroplusfour
No Result
View All Result
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
No Result
View All Result
Zeroplusfour
No Result
View All Result
Home Code Solutions Hackerrank Algorithms

Fairy Chess – HackerRank Solution

Fairy Chess - HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

bhautik bhalala by bhautik bhalala
June 9, 2022
Reading Time: 1 min read
0
15 Days to learn SQL Hard SQL(Advanced)-Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution alt text

Spread the love

Table of Contents

  • Fairy Chess – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
  • Solutions of Algorithms Data Structures Hard HackerRank:
    • Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
  • C++ Fairy Chess HackerRank Solution
  • Java Fairy Chess HackerRank Solution
  • Python 3 Fairy Chess HackerRank Solution
  • Python 2 Fairy Chess HackerRank Solution
  • C Fairy Chess HackerRank Solution
    • Warmup Implementation Strings Sorting Search Graph Theory Greedy Dynamic Programming Constructive Algorithms Bit Manipulation Recursion Game Theory NP Complete Debugging
    • Leave a comment below
      • Related posts:

Fairy Chess – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

Solutions of Algorithms Data Structures Hard HackerRank:

Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts

C++ Fairy Chess HackerRank Solution


Copy Code Copied Use a different Browser

#include <iostream>
#include <cstring>

using namespace std;

#define long long long

const int maxn = 210;
const int mod = 1000000007;

int n, m, s;
char map[maxn][maxn];
long ans[maxn][maxn];
long sum[maxn][2*maxn];

void init()
{
	cin>>n>>m>>s;
	for(int i=0; i<n; ++i)
		cin>>map[i];
}

long getsum(int x, int y)
{
	if(x<0) {
		y += x;
		x = 0;
	}
	if(x>=n) {
		y = y - x + n - 1;
		x = n - 1;
	}
	if(y<0)
		return 0;
	return sum[x][y];
}

void calc_sum()
{
	for(int j=0; j<2*n; ++j)
		for(int i=0; i<n; ++i)
		{
			if(j>=n)
				sum[i][j] = 0;
			else
				sum[i][j] = ans[i][j];
			sum[i][j] = (sum[i][j] + getsum(i-1, j-1) + getsum(i+1, j-1) - getsum(i, j-2) + mod) % mod;
		}
}

void solve() {
	memset(ans, 0, sizeof(ans));
	for(int i=0; i<n; ++i)
		for(int j=0; j<n; ++j)
			if(map[i][j] == 'L')
				ans[i][j] = 1;
	for(int k=1; k<=m; ++k) {
		calc_sum();
		for(int i=0; i<n; ++i)
			for(int j=0; j<n; ++j)
				if(map[i][j] == 'P')
					ans[i][j] = 0;
				else
				{
					ans[i][j] = (getsum(i, j+s) - getsum(i-s-1, j-1) - getsum(i+s+1, j-1) + getsum(i, j-s-2) + mod + mod)%mod;
					ans[i][j] = (ans[i][j] + getsum(i, j+s-1) - getsum(i-s, j-1) - getsum(i+s, j-1) + getsum(i, j-s-1) + mod + mod)%mod;
				}
	}

	long res = 0;
	for(int i=0; i<n; ++i)
		for(int j=0; j<n; ++j)
			res = (res + ans[i][j])%mod;
	cout<<res<<endl;
}

int main() {
	int t;
	cin>>t;
	while(t--)
	{
		init();
		solve();
	}
}

Java Fairy Chess HackerRank Solution


Copy Code Copied Use a different Browser

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

class FairyChessSolver {

	static final class Operation {

		private static final int FINITE_FIELD_MODULO = 1000000007;

		public static int add(int a, int b) {
			int r = a + b;
			return r - (((FINITE_FIELD_MODULO - r - 1) >> 31) & FINITE_FIELD_MODULO);
		}

		public static int sub(int a, int b) {
			int r = a - b;
			return r + (FINITE_FIELD_MODULO & (r >> 31));
		}
	}

	private static char PAWN_SYMBOL = 'P';
	private static char LEAPER_SYMBOL = 'L';
	private static int EMPTY = 0;
	private static int PAWN = 1;

	private int n, m, s;
	private int leaperRow, leaperCol;
	private int[][] board;
	
	public FairyChessSolver(int boardSize, int moves, int s, String[] board) {
		this.n = boardSize;
		this.board = new int[this.n][this.n];
		this.m = moves;
		this.s = s;
		for (int i = 0; i < boardSize; i++) {
			String row = board[i];
			int[] thisRow = this.board[i];
			for (int j = 0; j < boardSize; j++) {
				if (row.charAt(j) == PAWN_SYMBOL) {
					thisRow[j] = PAWN;
				}
				else if (row.charAt(j) == LEAPER_SYMBOL) {
					leaperRow = i;
					leaperCol = j;
				}
			}
		}
	}

	public void solve() {
		int[][] ways = new int[n][n];
		ways[leaperRow][leaperCol] =  1;

		int[][] cWays = new int[n][n];
		int[][] s1 = new int[n+s][n+s];
		int[][] s2 = new int[n+s][n+s];
		for (int move = 0; move < m; move++) {

			// - evaluate sums of diagonal stripes of length s / s-1
			// -- i == 0
			for (int j = s; j < n + s; j++) {
				s1[0][j] = ways[0][j-s];
			}
			
			// -- i -> [1, s]
			for (int i = 1; i <= s; i++) {
				int[] s1i = s1[i];
				int[] s1i1 = s1[i-1];
				if (i < n) {
					int[] wi = ways[i];
					for (int j = 0; j < s; j++) {
						s1i[j] = s1i1[j+1];
					}
					for (int j = s, l = n + s - 1; j < l; j++) {
						s1i[j] = Operation.add(s1i1[j+1], wi[j-s]);
					}
					s1i[n+s-1] = wi[n-1];
				}
				else {
					for (int j = 0, l = n + s - 1; j < l; j++) {
						s1i[j] = s1i1[j+1];
					}
				}
			}

			// -- i -> (s, n+s)
			for (int i = s + 1; i < n + s; i++) {
				int[] s1i = s1[i];
				int[] s1i1 = s1[i-1];
				int[] wis1 = ways[i-s-1];
				if (i < n) {
					int[] wi = ways[i];
					for (int j = 0; j < s; j++) {
						if (j+1 < n) {
							s1i[j] = Operation.sub(s1i1[j+1], wis1[j+1]);
						}
						else {
							s1i[j] = s1i1[j+1];							
						}
					}
					for (int j = s, l = n + s - 1; j < l; j++) {
						if (j+1 < n) {
							s1i[j] = Operation.sub(Operation.add(s1i1[j+1], wi[j-s]), wis1[j+1]);
						}
						else {
							s1i[j] = Operation.add(s1i1[j+1], wi[j-s]);
						}
					}
					s1i[n+s-1] = wi[n-1];
				}
				else {
					for (int j = 0, l = n - 1; j < l; j++) {
						s1i[j] = Operation.sub(s1i1[j+1], wis1[j+1]);
					}
					for (int j = n - 1, l = n + s - 1; j < l; j++) {
						s1i[j] = s1i1[j+1];
					}
				}
			}

			// -- i == 0
			for (int j = 0; j < n; j++) {
				s2[0][j] = ways[0][j];
			}
			
			// -- i -> [1, s)
			for (int i = 1; i < s; i++) {
				int[] s2i = s2[i];
				int[] s2i1 = s2[i-1];
				if (i < n) {
					int[] wi = ways[i];
					s2i[0] = wi[0];
					for (int j = 1; j < n; j++) {
						s2i[j] = Operation.add(s2i1[j-1], wi[j]);
					}
					for (int j = n, l = n + s; j < l; j++) {
						s2i[j] = s2i1[j-1];
					}
				}
				else {
					for (int j = 1, l = n + s; j < l; j++) {
						s2i[j] = s2i1[j-1];
					}
				}
			}
			
			// -- i -> [s, n+s)
			for (int i = s; i < n + s; i++) {
				int[] s2i = s2[i];
				int[] s2i1 = s2[i-1];
				int[] wis = ways[i-s];
				if (i < n) {
					int[] wi = ways[i];
					s2i[0] = wi[0];
					// --- j -> [1, s)
					for (int j = 1; j < s; j++) {
						if (j < n) {
							s2[i][j] = Operation.add(s2i1[j-1], wi[j]);
						}
						else {
							s2i[j] = s2i1[j-1];
						}
					}
					// --- j -> [s, s+n)
					for (int j = s, l = n + s; j < l; j++) {
						if (j < n) {
							s2i[j] = Operation.sub(Operation.add(s2i1[j-1], wi[j]), wis[j-s]);
						}
						else {
							s2i[j] = Operation.sub(s2i1[j-1], wis[j-s]);
						}
					}			
				}
				else {
					// --- j -> [1, s)
					for (int j = 1; j < s; j++) {
						s2i[j] = s2i1[j-1];
					}
					// --- j -> [s, s+n)
					for (int j = s, l = n + s; j < l; j++) {
						s2i[j] = Operation.sub(s2i1[j-1], wis[j-s]);
					}			
				}
			}

			// - evaluate updated "ways to move" matrix
			// -- evaluate after-move value of cell (0, 0)
			int value = 0;
			for (int i = 0; i <= Math.min(s, n-1); i++) {
				int[] wi = ways[i];
				for (int j = 0, l = Math.min(s-i, n-1); j <= l; j++) {
					value = Operation.add(value, wi[j]);
				}
			}
			cWays[0][0] = value;

			for (int i = 0; i < n; i++) {
				if (i > 0) {
					value = cWays[i-1][0];
					// - add: s1(i+s, s)
					value = Operation.add(value, s1[i+s][s]);
					// - sub: s2(i-1, s), ways(i-s-1, 0)
					if (i > s) {
						value = Operation.sub(Operation.sub(value, s2[i-1][s]), ways[i-s-1][0]);
					}
					else {
						value = Operation.sub(value, s2[i-1][s]);
					}
					// - set value
					cWays[i][0] = value;
					
					// - i > 0
					int[] cwi = cWays[i];
					int[] s1is = s1[i+s];
					int[] s1i = s1[i];
					int[] s2i1 = s2[i-1];
					int[] s2is = s2[i+s];
					for (int j = 1; j < n; j++) {
						value = cwi[j-1];
						// - add: s1(i+s, j+s), s2(i-1, j+s-1)
						value = Operation.add(Operation.add(value, s1is[j+s]), s2i1[j+s-1]);
						// - sub: s1(i, j-1), s2(i+s, j-1)
						value = Operation.sub(Operation.sub(value, s1i[j-1]), s2is[j-1]);
						// - set value
						cwi[j] = value;
					}
				}
				else {
					// - i == 0
					for (int j = 1; j < n; j++) {
						value = cWays[0][j-1];
						// - add: s1(i+s, j+s)
						value = Operation.add(value, s1[s][j+s]);
						// - sub: s1(i, j-1), s2(i+s, j-1)
						value = Operation.sub(Operation.sub(value, s1[0][j-1]), s2[s][j-1]);
						// - set value
						cWays[0][j] = value;
					}
				}
			}
			// - clear occupied cells 
			for (int i = 0; i < n; i++) {
				int[] bi = board[i];
				for (int j = 0; j < n; j++) {
					if (bi[j] != EMPTY) {
						cWays[i][j] = 0;
					}
				}
			}
			int[][] tmp = ways;
			ways = cWays;
			cWays = tmp;
		}
		int result = 0;
		for (int i = 0; i < n; i++) {
			int[] wi = ways[i];
			for (int j = 0; j < n; j++) {
				result = Operation.add(result, wi[j]);
			}
		}
		System.out.println(result);
	}
}

public class Solution {
	static public void main(String[] args) {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 64 << 10);
			int testsNumber = Integer.parseInt(br.readLine().trim());
			for (int test = 0; test < testsNumber; test++) {
				StringTokenizer tokenizer = new StringTokenizer(br.readLine());
				int n = Integer.parseInt(tokenizer.nextToken());
				int m = Integer.parseInt(tokenizer.nextToken());
				int s = Integer.parseInt(tokenizer.nextToken());
				String[] board = new String[n];
				for (int i = 0; i < n; i++) {
					board[i] = br.readLine().trim();
				}
				new FairyChessSolver(n, m, s, board).solve();
			}
		}
		catch (Exception e) {
			System.err.println("Error:" + e.getMessage());
		}
	}
}

 



Python 3 Fairy Chess HackerRank Solution


Copy Code Copied Use a different Browser

 



Python 2 Fairy Chess HackerRank Solution


Copy Code Copied Use a different Browser

import numpy

modulus = 1000000007

def expandBoard(board, S, eboard=None):
    (N,N2) = board.shape
    assert N==N2
    NS = N+2*S+2
    if eboard is None:
        eboard = numpy.zeros((NS,NS), numpy.longlong)
    eboard[S+1:S+N+1,S+1:S+N+1] = board
    return eboard

def contractBoard(eboard, S):
    (NS, NS2) = eboard.shape
    N = NS-2*S-2
    board = eboard[S+1:S+N+1, S+1:S+N+1]
    return board

def leftDiagonal(eboard, S, L=None):
    if L is None:
        L = numpy.zeros(eboard.shape, numpy.longlong)
    n = eboard.shape[0]
    L[0, :] = eboard[0, :]
    L[:, 0] = eboard[:, 0]
    for i in range(S+1, n-1):
        #L[i, 1:n-1] = (eboard[i, 1:n-1] + L[i-1, 0:n-2])%modulus
        numpy.add(eboard[i,1:n-1], L[i-1,0:n-2], L[i,1:n-1])
    #numpy.mod(L, modulus, L)
    return L

def rightDiagonal(eboard, S, R=None):
    if R is None:
        R = numpy.zeros(eboard.shape, numpy.longlong)
    n = eboard.shape[0]
    R[0, :] = eboard[0, :]
    R[:, n-1] = eboard[:, n-1]
    for i in range(S+1, n-1):
        #R[i, 0:n-2] = (eboard[i, 0:n-2] + R[i-1, 1:n-1])%modulus
        numpy.add(eboard[i, 0:n-2], R[i-1, 1:n-1], R[i, 0:n-2])
    #numpy.mod(R, modulus, R)
    return R

def ULCornerSum(eboard, S):
    "could optimize"
    t = 0
    s2 = 2*S+2
    for i in xrange(S+1):
        ##pr "ul", eboard[i, S+1: s2-i], i, S+1, s2-i
        t += eboard[S+1+i, S+1: s2-i].sum()
    return t%modulus
    #s2 = 2*S+2
    #t = 0
    #for i in xrange(s2):
    #    t+= eboard[i, 0:(s2-i)].sum()
    #return t

def RDiag(R, istart, jstart, length, N, out=None):
    ##pr "Rdiag", (istart, jstart, length, N)
    ##pr istart-length, istart-length+N
    ##pr istart-1, istart-1+N
    #N1 = N-1
    if out is None:
        out = numpy.zeros( (N,), numpy.longlong)
    assert jstart>=length
    out[:] = R[istart+length:istart+length+N, jstart-length]
    if jstart>0:
        #out = out - R[istart-1:istart-1+N, jstart+1]
        numpy.subtract(out, R[istart-1:istart-1+N, jstart+1], out)
    numpy.mod(out, modulus, out)
    return out

def LDiag(L, istart, jstart, length, N, out=None):
    if out is None:
        out = numpy.zeros( (N,), numpy.longlong)
    #N1 = N-1
    out[:] = L[istart+length:istart+length+N, jstart+length]
    if istart>0 and jstart>0:
        #out = out - L[istart-1:istart-1+N, jstart-1]
        numpy.subtract(out, L[istart-1:istart-1+N, jstart-1], out)
    numpy.mod(out, modulus, out)
    return out

def f(N,M,S,board):
    ##pr
    ##pr "f", (N,M,S)
    moves = numpy.zeros((N,N), numpy.longlong)
    nextmoves = numpy.zeros((N,N), numpy.longlong)
    pawns = numpy.ones((N,N), numpy.longlong)
    for i in xrange(N):
        for j in xrange(N):
            b = board[i][j]
            if b=="P":
                pawns[i][j] = 0
            if b=="L":
                Li = i
                Lj = j
                moves[i][j] = 1
    ##pr moves, "moves"
    ##pr pawns, "pawns"
    m = expandBoard(moves, S)
    D = numpy.zeros(m.shape, numpy.longlong)
    base = Rm = Lm = Rp = Lp = m = L = R = None
    for c in xrange(M):
        m = expandBoard(moves, S, m)
        #D = numpy.zeros(m.shape, numpy.longlong) # could reuse m
        #D[:,:] = 0 # not needed?
        ##pr m, "m"
        D[S+1,S+1] = ULCornerSum(m, S) # could optimize
        ##pr D, "ulcorner", S
        R = rightDiagonal(m, S, R)
        ##pr R, "R"
        L = leftDiagonal(m, S, L)
        ##pr L, "L"
        first = S+1
        second = S+2
        last = S+N+1
        dstart = 1
        dend = dstart+2*S
        for i in xrange(S+2, S+N+1):
            Lm0 = L[i-1,dend]-L[i-1-first,S]
            Rp0 = R[i+S,first]-R[i-1,dend+1]
            #D[i,first] = D[i-1,first]-(L[i-1,dstart]-L[i-1-first,S])+(R[i+S,S]-R[i-1,2*S+2])
            ##pr "D[i-1,first]", D[i-1,first], "Lm", Lm, "Rp", Rp
            D[i,first] = D[i-1,first]-Lm0+Rp0
        ##pr D, "first column diamonds"
        for j in range(S+2, S+N+1):
            base = D[S+1:S+1+N, j-1]
            Rm = RDiag(R, dstart, j-1, S-1, N, Rm)
            Lm = LDiag(L, first, j-1-S, S, N, Lm)
            Rp = RDiag(R, first, j+S, S, N, Rp)
            Lp = LDiag(L, dstart, j, S-1, N, Lp)
            numpy.add(Rp, Lp, Rp)
            numpy.add(Rp, base, Rp)
            numpy.subtract(Rp, Rm, Rp)
            numpy.subtract(Rp, Lm, Rp)
            D[S+1:S+1+N, j] = Rp #(base - Rm - Lm + Rp + Lp)%modulus
            #D[S+1:S+1+N,j] = ( D[S+1:S+1+N,j-1] -
            #                   Rdiag(R, 0, j-1, S-1, N) -
            #                   Ldiag(L, S, j-S-1, S, N) +
            #                   Rdiag(R, S, j+S, S, N) +
            #                   Ldiag(L, 0, j, S-1, N))
            ##pr D, "col", j, "diamonds"
        #pr D, "final diamonds"
        moves = contractBoard(D, S)
        #moves = (moves * pawns)%modulus
        numpy.multiply(moves, pawns, moves)
        numpy.mod(moves, modulus, moves)
        #pr moves, "contracted moves"
        m,D = D,m
    return (moves.sum())%modulus

def tt(N,M,S, check=True):
    import random
    from random import randint
    import time
    import fairyb
    random.seed(N)
    b = [ ["."] * N for i in xrange(N) ]
    pcount = randint(0,N*N/2)
    for i in xrange(pcount):
        b[ randint(0,N-1)][randint(0,N-1) ] = "P"
    b[ randint(0,N-1)][randint(0,N-1)] = "L"
    #for x in b:
    #    print "".join(x)
    print
    now = time.time()
    t = f(N,M,S, b)
    elapsed = time.time()-now
    print t, elapsed
    if check:
        t2 = fairyb.f(N,M,S,b)
        print t, t2
        assert t==t2

if 1 and __name__=="__main__":
    import sys
    r = sys.stdin.readline
    T = int(r().strip())
    for c in range(T):
        (n,m,S) = map(int, r().split())
        board = []
        for i in xrange(n):
            line = r().strip()
            board.append(line)
        print f(n,m,S,board)



C Fairy Chess HackerRank Solution


Copy Code Copied Use a different Browser

#include <stdlib.h>
#include <stdio.h>
#include <strings.h>

#define MAX_WIDTH  200
#define MAX_MOVE 201
#define MODULAR 1000000007

#define FORMAT_RESULT(x) if (x >= MODULAR) {\
    x -= MODULAR;\
} else if (x < 0) {\
    x += MODULAR;\
}

char board[MAX_WIDTH][MAX_WIDTH];
int width; // board width
int max_step;  // step can move once
int max_moves;
int result[MAX_MOVE][MAX_WIDTH][MAX_WIDTH] = {0};
int cache_asc[2][MAX_WIDTH][MAX_WIDTH];
int cache_desc[2][MAX_WIDTH][MAX_WIDTH];
int read_index;
int write_index;

void
compute(int moves)
{
    int y, x, x1, y1, y2, x2, dx, dy;
    
    // (0, 0)
    for (y = 0; y < max_step; y++) {
        result[moves][0][0] += cache_desc[read_index][y][0];
        FORMAT_RESULT(result[moves][0][0]);
    }
    if (max_step < width) {
        result[moves][0][0] += cache_desc[read_index][max_step][0];
        FORMAT_RESULT(result[moves][0][0]);
    } else {
        if (1 < width) {
            result[moves][0][0] += cache_desc[read_index][max_step - 1][1];
            FORMAT_RESULT(result[moves][0][0]);
        }
    }
    cache_desc[write_index][0][0] = cache_asc[write_index][0][0] = board[0][0] == 'P' ? 0 : result[moves][0][0];

    // [(1, 0), (width - 1, 0)]
    for (x = 1; x < width; x++) {
        result[moves][0][x] = result[moves][0][x - 1];

        x1 = x;
        y1 = max_step;
        if (y1 >= width) {
            dy = y1 - width + 1;
            y1 -= dy;
            x1 += dy;
        }
        if (x1 < width) {
            result[moves][0][x] += cache_desc[read_index][y1][x1];
            FORMAT_RESULT(result[moves][0][x]);
        }

        x1 = x - 1;
        y1 = max_step;
        if (y1 >= width) {
            dy = y1 - width + 1;
            y1 -= dy;
            x1 -= dy;
        }
        if (x1 >= 0) {
            result[moves][0][x] -= cache_asc[read_index][y1][x1];
            FORMAT_RESULT(result[moves][0][x]);
        }

        cache_desc[write_index][0][x] = cache_asc[write_index][0][x] = board[0][x] == 'P' ? 0 : result[moves][0][x];
    }

    // [(0, 1), (width - 1, width - 1)]
    for (y = 1; y < width; y++) {
        for (x = 0; x < width; x++) {
            result[moves][y][x] = result[moves][y - 1][x];

            x1 = x;
            y1 = y + max_step;
            x2 = x + max_step;
            y2 = y;
            if (y1 >= width) {
                dy = y1 - width + 1;
                y1 -= dy;
                x1 += dy;
            }
            if (x1 < width) {
                if (x2 >= width - 1) {
                    result[moves][y][x] += cache_desc[read_index][y1][x1];
                    FORMAT_RESULT(result[moves][y][x]);
                } else {
                    result[moves][y][x] += cache_desc[read_index][y1][x1] - cache_desc[read_index][y2 - 1][x2 + 1];
                    FORMAT_RESULT(result[moves][y][x]);
                }
            }
            x1 = x;
            y1 = y + max_step;
            x2 = x - max_step;
            y2 = y;
            if (y1 >= width) {
                dy = y1 - width + 1;
                y1 -= dy;
                x1 -= dy;
            }
            if (x1 >= 0) {
                if (x2 <= 0) {
                    result[moves][y][x] += cache_asc[read_index][y1][x1];
                    FORMAT_RESULT(result[moves][y][x]);
                } else {
                    result[moves][y][x] += cache_asc[read_index][y1][x1] - cache_asc[read_index][y2 - 1][x2 - 1];
                    FORMAT_RESULT(result[moves][y][x]);
                }
            }
            if (y + max_step < width) {
                result[moves][y][x] -= result[moves - 1][y + max_step][x];
                FORMAT_RESULT(result[moves][y][x]);
            }

            x1 = x + max_step;
            y1 = y - 1;
            x2 = x;
            y2 = y - 1 - max_step;
            if (x1 >= width) {
                dx = x1 - width + 1;
                y1 -= dx;
                x1 -= dx;
            }
            if (y1 >= 0) {
                if (y2 <= 0 || x2 == 0) {
                    result[moves][y][x] -= cache_asc[read_index][y1][x1];
                    FORMAT_RESULT(result[moves][y][x]);
                } else {
                    result[moves][y][x] -= cache_asc[read_index][y1][x1] - cache_asc[read_index][y2 - 1][x2 - 1];
                    FORMAT_RESULT(result[moves][y][x]);
                }
            }

            x1 = x - max_step;
            y1 = y - 1;
            x2 = x;
            y2 = y - 1 - max_step;
            if (x1 < 0) {
                dx = -x1;
                x1 += dx;
                y1 -= dx;
            }
            if (y1 >= 0) {
                if (y2 <= 0 || x2 == width - 1) {
                    result[moves][y][x] -= cache_desc[read_index][y1][x1];
                    FORMAT_RESULT(result[moves][y][x]);
                } else {
                    result[moves][y][x] -= cache_desc[read_index][y1][x1] - cache_desc[read_index][y2 - 1][x2 + 1];
                    FORMAT_RESULT(result[moves][y][x]);
                }
            }
            if (y - 1 - max_step >= 0) {
                result[moves][y][x] += result[moves - 1][y - 1 - max_step][x];
                FORMAT_RESULT(result[moves][y][x]);
            }


            cache_asc[write_index][y][x] = x > 0 ? cache_asc[write_index][y - 1][x - 1] : 0;
            cache_desc[write_index][y][x] = (x < width - 1) ? cache_desc[write_index][y - 1][x + 1] : 0;
            if (board[y][x] != 'P') {
                cache_desc[write_index][y][x] += result[moves][y][x];
                FORMAT_RESULT(cache_desc[write_index][y][x]);
                cache_asc[write_index][y][x] += result[moves][y][x];
                FORMAT_RESULT(cache_asc[write_index][y][x]);
            }
        }
    }

    for (y = 0; y < width; y++) {
        for (x = 0; x < width; x++) {
            if (board[y][x] == 'P') {
                result[moves][y][x] = 0;
            }
        }
    }
}

int
main (int argc, char *argv[])
{
    int num_case;
    int x, y, moves, sum, i, j;

    scanf("%d", &num_case);
    while (num_case--) {
        bzero(result, sizeof(int) * MAX_MOVE * MAX_WIDTH * MAX_WIDTH);
        bzero(cache_asc, sizeof(int) * 2 * MAX_WIDTH * MAX_WIDTH);
        bzero(cache_desc, sizeof(int) * 2 * MAX_WIDTH * MAX_WIDTH);

        scanf("%d %d %d", &width, &max_moves, &max_step);
        for (y = width - 1; y >= 0; y--) {
            scanf("%s", board[y]);
        }

        read_index = 0;
        write_index = 1;
        for (y = 0; y < width; y++) {
            for (x = 0; x < width; x++) {
                if (board[y][x] == 'L') {
                    result[0][y][x] = 1;
                }
                if (x > 0 && y > 0) {
                    cache_asc[read_index][y][x] = result[0][y][x] + cache_asc[read_index][y - 1][x - 1];
                } else {
                    cache_asc[read_index][y][x] = result[0][y][x];
                }
                if (x < width && y > 0) {
                    cache_desc[read_index][y][x] = result[0][y][x] + cache_desc[read_index][y - 1][x + 1];
                } else {
                    cache_desc[read_index][y][x] = result[0][y][x];
                }
            }
        }

        for (moves = 1; moves <= max_moves; moves++) {
            compute(moves);
            if (read_index == 1) {
                write_index = 1;
                read_index = 0;
            } else {
                write_index = 0;
                read_index = 1;
            }
        }

        sum = 0;
        for (y = 0; y < width; y++) {
            for (x = 0; x < width; x++) {
                sum += result[max_moves][y][x];
                FORMAT_RESULT(sum);
            }
        }
        printf("%d\n", sum);
    }

    return 0;
}

/* vim: set ts=4 sw=4 sts=4 tw=100 et: */

 

Warmup
Implementation
Strings
Sorting
Search
Graph Theory
Greedy
Dynamic Programming
Constructive Algorithms
Bit Manipulation
Recursion
Game Theory
NP Complete
Debugging

Leave a comment below

 

Related posts:

15 Days to learn SQL Hard SQL(Advanced)-SolutionSimilar Pair – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDijkstra: Shortest Reach 2 – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionJim and his LAN Party – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionChoosing White Balls – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionFlipping bits – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionLily’s Homework – HackerRank Solution
Tags: Cc++14Fairy Chessfull solutionGoHackerRank Solutionjavajava 15java 7java 8java8javascriptpypy 3Python 2python 3
ShareTweetPin
bhautik bhalala

bhautik bhalala

Related Posts

Leetcode All Problems Solutions
Code Solutions

Exclusive Time of Functions – LeetCode Solution

by admin
October 5, 2022
0
29

Exclusive Time of Functions - LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions...

Read more
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
32
Leetcode All Problems Solutions

Course Schedule III – LeetCode Solution

October 5, 2022
25
Leetcode All Problems Solutions

Maximum Product of Three Numbers – LeetCode Solution

September 11, 2022
52
Leetcode All Problems Solutions

Task Scheduler – LeetCode Solution

September 11, 2022
119
Leetcode All Problems Solutions

Valid Triangle Number – LeetCode Solution

September 11, 2022
28
Next Post
15 Days to learn SQL Hard SQL(Advanced)-Solution

Suffix Rotation - HackerRank Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution

New Year Present - HackerRank Solution

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

15 Days to learn SQL Hard SQL(Advanced)-SolutionSimilar Pair – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDijkstra: Shortest Reach 2 – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionJim and his LAN Party – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionChoosing White Balls – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionFlipping bits – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionLily’s Homework – HackerRank Solution

Categories

  • Algorithms
  • Anime
  • Biography
  • Business
  • Code Solutions
  • Cosmos
  • Countdowns
  • Culture
  • Economy
  • Education
  • Entertainment
  • Finance
  • Games
  • Hackerrank
  • Health
  • How to
  • Investment
  • LeetCode
  • Lifestyle
  • LINUX SHELL
  • Manga
  • News
  • Opinion
  • Politics
  • Sports
  • SQL
  • Tech
  • Travel
  • Uncategorized
  • Updates
  • World
  • DMCA
  • Home
  • My account
  • Privacy Policy
  • Top Posts

Recent Blogs

Leetcode All Problems Solutions

Exclusive Time of Functions – LeetCode Solution

October 5, 2022
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
Leetcode All Problems Solutions
Code Solutions

Number of Boomerangs – LeetCode Solution

September 9, 2022
24
TOP 10 MOST COMMON FAMILY ISSUES: you should know them -...
How to

TOP 10 MOST COMMON FAMILY ISSUES: you should know them

May 19, 2022
3
Leetcode All Problems Solutions
Code Solutions

Construct Binary Tree from Preorder and Inorder Traversal – LeetCode Solution

September 3, 2022
56
Biography

Pooja Hegde Net Worth, Age, Height , Achivements and more

September 8, 2022
1

© 2022 ZeroPlusFour - Latest News & Blog.

No Result
View All Result
  • Home
  • Category
    • Business
    • Culture
    • Economy
    • Lifestyle
    • Health
    • Travel
    • Opinion
    • Politics
    • Tech
  • Landing Page
  • Support Forum
  • Contact Us

© 2022 ZeroPlusFour - Latest News & Blog.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?