From 70384c40ba45e2adf54692dd4dfca319945636c6 Mon Sep 17 00:00:00 2001 From: S ANEERUDH Date: Sun, 5 Oct 2025 23:42:35 +0530 Subject: [PATCH] Completed Graph-1 --- ballinaMaze.cpp | 43 +++++++++++++++++++++++++++++++++++++++++++ townJudge.cpp | 25 +++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 ballinaMaze.cpp create mode 100644 townJudge.cpp diff --git a/ballinaMaze.cpp b/ballinaMaze.cpp new file mode 100644 index 0000000..7487feb --- /dev/null +++ b/ballinaMaze.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +using namespace std; +/* +We keep rolling the ball in all directions until it hits a wall, starting from the current position. +Each time we land on a new stopping cell, we check if it's the destination and then DFS from there. +We mark visited cells as -1 to avoid revisiting the same paths again. +*/ +class Solution{ + vector> dirs; + int m, n; + + bool dfs(vector>& maze, int i, int j, vector& destination){ + if(destination[0] == i && destination[1] == j) return true; + if(maze[i][j] == -1) return false; + + maze[i][j] = -1; + for(auto& dir : dirs){ + int r = dir[0] + i; + int c = dir[1] + j; + + while(r >= 0 && c >= 0 && r < m && c < n && maze[r][c] != 1){ + r += dir[0]; + c += dir[1]; + } + + r -= dir[0]; + c -= dir[1]; + + if(dfs(maze, r, c, destination)) return true; + } + return false; + } +public: + bool hasPath(vector>& maze, vector& start, vector& destination){ + dirs = {{-1, 0}, {1,0}, {0,1}, {0, -1}}; + m = maze.size(); + n = maze[0].size(); + + return dfs(maze, start[0], start[1], destination); + } +}; diff --git a/townJudge.cpp b/townJudge.cpp new file mode 100644 index 0000000..468280e --- /dev/null +++ b/townJudge.cpp @@ -0,0 +1,25 @@ +#include +#include +#include +using namespace std; +/* +We use an array to count trust levels: losing trust (out-degree) subtracts, gaining trust (in-degree) adds. +The town judge should be trusted by everyone else but trust no one. +So we just find the person with an in-degree of n−1. +*/ +class Solution{ +public: + int findJudge(int n, vector>& trust){ + vector inDegrees(n+1); + + for(auto& it : trust){ + inDegrees[it[0]]--; + inDegrees[it[1]]++; + } + + for(int i = 0; i <= n; i++){ + if(inDegrees[i] == n-1) return i; + } + return -1; + } +};