• Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
Wednesday, February 1, 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 Updates

Frog in Maze – HackerRank Solution

Frog in Maze - HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

bhautik bhalala by bhautik bhalala
May 27, 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

  • Frog in Maze – 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++ Frog in Maze HackerRank Solution
  • Java Frog in Maze HackerRank Solution
    • Leave a comment below
      • Related posts:

Frog in Maze – 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++ Frog in Maze HackerRank Solution


Copy Code Copied Use a different Browser

#include <bits/stdc++.h>
#define endl '\n'

#define double long double

using namespace std;
const int MAXN = (42);
const double eps = 1e-12;

vector<double> gauss(vector<vector<double>> &a)
{
	int n = a.size(), m = a[0].size() - 1;

	vector<int> where(m, -1);
	for(int col = 0, row = 0; col < m && row < n; col++)
    {
    	int sel = row;
        for(int i = row; i < n; i++)
        	if(abs(a[i][col]) > abs(a[sel][col]))
        		sel = i;

		if(abs(a[sel][col]) < eps) { where[col] = -1; continue; }

        for(int i = col; i <= m; i++)
			swap(a[sel][i], a[row][i]);
		where[col] = row;

		for(int i = 0; i < n; i++)
			if(i != row)
			{
				if(abs(a[i][col]) < eps) continue;
            	double c = a[i][col] / a[row][col];
            	for(int j = 0; j <= m; j++)
                    a[i][j] -= c * a[row][j];
			}

		row++;
    }

    vector<double> ans(m, 0);
    for(int i = 0; i < m; i++)
        if(where[i] != -1)
			ans[i] = a[where[i]][m] / a[where[i]][i];

    for(int i = 0; i < n; i++)
	{
		double sum = a[i][m];
		for(int j = 0; j < m; j++)
			sum -= ans[j] * a[i][j];

		if(abs(sum) > eps) return vector<double>();
	}

	return ans;
}

int n, m, k;
string a[MAXN];
int nxt_x[MAXN][MAXN], nxt_y[MAXN][MAXN];

void read()
{
    cin >> n >> m >> k;
    for(int i = 0; i < n; i++)
        cin >> a[i];

    for(int i = 0; i < n; i++)
        for(int j = 0; j < m; j++)
            nxt_x[i][j] = i, nxt_y[i][j] = j;

    for(int i = 0; i < k; i++)
    {
        int x1, y1, x2, y2;
        cin >> x1 >> y1 >> x2 >> y2;
        x1--; y1--; x2--; y2--;
        nxt_x[x1][y1] = x2; nxt_y[x1][y1] = y2;
        nxt_x[x2][y2] = x1; nxt_y[x2][y2] = y1;
    }
}

int N;
int encode(int x, int y) { return x * m + y; }

int dirx[4] = {0, 0, 1, -1};
int diry[4] = {1, -1, 0, 0};

bool ok(int x, int y)
{
    if(x >= n || y >= m || x < 0 || y < 0) return false;
    return a[x][y] != '#';
}

void solve()
{
    N = n * m;
    vector<vector<double> > matr;
    vector<double> zero(N + 1, 0);

    for(int i = 0; i < n; i++)
        for(int j = 0; j < m; j++)
        {
            if(a[i][j] == '#') { matr.push_back(zero); continue; }
            else if(a[i][j] == '*') { matr.push_back(zero), matr[matr.size() - 1][encode(i, j)] = 1; continue; }
            else if(a[i][j] == '%') { matr.push_back(zero), matr[matr.size() - 1][encode(i, j)] = 1;  matr[matr.size() - 1][N] = 1; continue; }

            vector<int> adj;
            for(int d = 0; d < 4; d++)
                if(ok(i + dirx[d], j + diry[d]))
                    adj.push_back(encode(nxt_x[i + dirx[d]][j + diry[d]], nxt_y[i + dirx[d]][j + diry[d]]));

            matr.push_back(zero);
            matr[matr.size() - 1][encode(i, j)] = 1;

            for(int v: adj)
                matr[matr.size() - 1][v] = -((double)1 / (double)adj.size());
        }

    vector<double> ans = gauss(matr);

    for(int i = 0; i < n; i++)
        for(int j = 0; j < m; j++)
            if(a[i][j] == 'A')
            {
                cout << setprecision(9) << fixed << ans[encode(i, j)] << endl;
                return;
            }
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	read();
	solve();
	return 0;
}

Java Frog in Maze HackerRank Solution


Copy Code Copied Use a different Browser

 

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Solution {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        FrogInMaze solver = new FrogInMaze();
        solver.solve(1, in, out);
        out.close();
    }

    static class FrogInMaze {
        public int[] dx = {-1, 0, 1, 0};
        public int[] dy = {0, -1, 0, 1};
        public int[][] ts;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
            char[][] grid = new char[n][m];
            for (int i = 0; i < n; i++) {
                grid[i] = in.next().toCharArray();
            }
            int[][][] neighbor = new int[n][m][];
            ts = new int[k][4];
            for (int i = 0; i < k; i++) {
                for (int j = 0; j < 4; j++)
                    ts[i][j] = in.nextInt() - 1;
                neighbor[ts[i][0]][ts[i][1]] = new int[]{ts[i][2], ts[i][3]};
                neighbor[ts[i][2]][ts[i][3]] = new int[]{ts[i][0], ts[i][1]};
            }

            double[][] mat = new double[n * m][n * m + 1];
            int sx = 0, sy = 0;
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    mat[i * m + j][i * m + j] = 1;

                    if (grid[i][j] == '%') {
                        mat[i * m + j][n * m] = 1;
                        continue;
                    }
                    if (grid[i][j] == '*' || grid[i][j] == '#') {
                        mat[i * m + j][n * m] = 0;
                        continue;
                    }

                    if (grid[i][j] == 'A') {
                        sx = i;
                        sy = j;
                    }


                    int avail = 0;
                    for (int r = 0; r < 4; r++) {
                        int ni = i + dx[r], nj = j + dy[r];
                        if (ni >= 0 && ni < n && nj >= 0 && nj < m && grid[ni][nj] != '#') {
                            avail++;
                        }
                    }

                    for (int r = 0; r < 4; r++) {
                        int ni = i + dx[r], nj = j + dy[r];
                        if (ni >= 0 && ni < n && nj >= 0 && nj < m && grid[ni][nj] != '#') {
                            if (neighbor[ni][nj] != null) {
                                int[] x = neighbor[ni][nj];
                                ni = x[0];
                                nj = x[1];
                            }
                            mat[i * m + j][ni * m + nj] -= 1.0 / avail;
                        }
                    }

                }
            }

            RowReduce.rref(mat);

            for (int i = 0; i < n * m; i++) {
                if (mat[i][sx * m + sy] > 1e-8) {
                    out.printf("%.10f\n", mat[i][n * m]);
                    return;
                }
            }
            out.println(0);
        }

    }

    static class RowReduce {
        public static void rref(double[][] M) {
            int row = M.length;
            if (row == 0)
                return;

            int col = M[0].length;

            int lead = 0;
            for (int r = 0; r < row; r++) {
                if (lead >= col)
                    return;

                int k = r;
                while (M[k][lead] == 0) {
                    k++;
                    if (k == row) {
                        k = r;
                        lead++;
                        if (lead == col)
                            return;
                    }
                }
                double[] temp = M[r];
                M[r] = M[k];
                M[k] = temp;

                double lv = M[r][lead];
                for (int j = 0; j < col; j++)
                    M[r][j] /= lv;

                for (int i = 0; i < row; i++) {
                    if (i != r) {
                        lv = M[i][lead];
                        for (int j = 0; j < col; j++)
                            M[i][j] -= lv * M[r][j];
                    }
                }
                lead++;
            }
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (this.numChars == -1) {
                throw new InputMismatchException();
            } else {
                if (this.curChar >= this.numChars) {
                    this.curChar = 0;

                    try {
                        this.numChars = this.stream.read(this.buf);
                    } catch (IOException var2) {
                        throw new InputMismatchException();
                    }

                    if (this.numChars <= 0) {
                        return -1;
                    }
                }

                return this.buf[this.curChar++];
            }
        }

        public int nextInt() {
            int c;
            for (c = this.read(); isSpaceChar(c); c = this.read()) {
                ;
            }

            byte sgn = 1;
            if (c == 45) {
                sgn = -1;
                c = this.read();
            }

            int res = 0;

            while (c >= 48 && c <= 57) {
                res *= 10;
                res += c - 48;
                c = this.read();
                if (isSpaceChar(c)) {
                    return res * sgn;
                }
            }

            throw new InputMismatchException();
        }

        public String next() {
            int c;
            while (isSpaceChar(c = this.read())) {
                ;
            }

            StringBuilder result = new StringBuilder();
            result.appendCodePoint(c);

            while (!isSpaceChar(c = this.read())) {
                result.appendCodePoint(c);
            }

            return result.toString();
        }

        public static boolean isSpaceChar(int c) {
            return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void printf(String format, Object... objects) {
            writer.printf(format, objects);
        }

        public void close() {
            writer.close();
        }

        public void println(int i) {
            writer.println(i);
        }

    }
}

 

Leave a comment below

 

Related posts:

15 Days to learn SQL Hard SQL(Advanced)-SolutionPseudo-Isomorphic Substrings – HackerRank Solution Default ThumbnailMaximum Subarray Sum – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSimilar Pair – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDiagonal Difference – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionToll Cost Digits – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionByteLandian Tours – HackerRank Solution
Tags: Cc++14Frog in Mazefull solutionGoHackerRank Solutionjavajava 15java 7java 8java8javascriptpypy 3Python 2python 3
ShareTweetPin
bhautik bhalala

bhautik bhalala

Related Posts

Updates

Find out how the cast and crew of Classroom of the Elite II prepare for each episode.

by admin
September 8, 2022
0
0

The cast and crew of Classroom of the Elite II discuss their approach to the show and how they prepare...

Read more

Nano Machine Anime Release Date: Plot, Trailer Announcement OUT

September 7, 2022
0
Lookism

Will There Be A Lookism Anime Adaptation from Manga? Release Date And Plot!

September 7, 2022
3

What Happened to Lazar Angelov?

September 5, 2022
3

Tony Beets Net Worth 2022: How Rich Is the Gold Rush Star?

September 5, 2022
1

Robert Kiyosaki Net Worth 2022: How he Made his Money

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

Tree Flow - HackerRank Solution

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

DAG Queries - 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)-SolutionPseudo-Isomorphic Substrings – HackerRank Solution Default ThumbnailMaximum Subarray Sum – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSimilar Pair – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDiagonal Difference – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionToll Cost Digits – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionByteLandian Tours – 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
Top 10 BEST TV Shows to Binge During Lockdown
Economy

Top 10 TV Shows to Binge Watch During Lockdown

March 31, 2022
3
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

The Longest Increasing Subsequence – HackerRank Solution

May 31, 2022
14
Leetcode All Problems Solutions
Code Solutions

Maximal Square – LeetCode Solution

September 6, 2022
42
Leetcode All Problems Solutions
Code Solutions

Two Sum- LeetCode Solution

September 2, 2022
1.1k

© 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?