Pathfinding algorithm isn’t finding correct route

I am attempting an online coding challenge wherein I am to implement a pathfinding algorithm that finds the shortest path between two points on a 2D grid. The code that is submitted is tested against a number of test cases that I, unfortunately, am unable to see, but it will however tell me if my answer for shortest distance is correct or not. My implementation of the A* algorithm returns a correct answer on 2/3 test cases and I cannot seem to figure out what scenario might create an incorrect answer on the third?

I have tried several of my own test cases and have gotten correct answers for all of those and at this point am feeling a little bit lost. There must be something small in my code that I am not seeing that is causing this third case to fail.

More details

  • The grid is w by h and contains only 1’s (passable) and 0’s (impassable) with every edge having a cost of 1 and the pathway cannot move diagonally It all starts with the FindPath function which is to return the length of the shortest path, or -1 if no path is available
  • pOutBuffer is used to contain the path taken from beginning to end (excluding the starting point). If multiple paths are available then any will be accepted. So it isnt looking for one path in particular
  • I know the issue is not the result of time or memory inefficiency. I has to be either the distance returned is incorrect, or the values in pOutBuffer are incorrect.

Any help would be greatly appreciated as I am just about out of ideas as to what could possibly be wrong here. Thank you.

#include <set> #include <vector> #include <tuple> #include <queue> #include <unordered_map>  inline int PositionToIndex(const int x, const int y, const int w, const int h) {     return x >= 0 && y >= 0 && x < w  && y < h? x + y * w : -1; }  inline std::pair<int, int> IndexToPosition(const int i, const int w) {     return std::make_pair<int, int>(i % w, i / w); }  inline int Heuristic(const int xa, const int ya, const int xb, const int yb) {     return std::abs(xa - xb) + std::abs(ya - yb); }  class Map { public:     const unsigned char* mapData;     int width, height;      const std::vector<std::pair<int, int>> directions = { {1,0}, {0,1}, {-1,0}, {0,-1} };      Map(const unsigned char* pMap, const int nMapWidth, const int nMapHeight)     {         mapData = pMap;         width = nMapWidth;         height = nMapHeight;     }      inline bool IsWithinBounds(const int x, const int y)      {         return x >= 0 && y >= 0 && x < width && y < height;     }      inline bool IsPassable(const int i)     {         return mapData[i] == char(1);     }       std::vector<int> GetNeighbours(const int i)     {         std::vector<int> ret;          int x, y, neighbourIndex;         std::tie(x, y) = IndexToPosition(i, width);          for (auto pair : directions)         {             neighbourIndex = PositionToIndex(x + pair.first, y + pair.second, width, height);             if (neighbourIndex >= 0 && IsWithinBounds(x + pair.first, y + pair.second) && IsPassable(neighbourIndex))                 ret.push_back(neighbourIndex);         }          return ret;     } };  int FindPath(const int nStartX, const int nStartY,     const int nTargetX, const int nTargetY,     const unsigned char* pMap, const int nMapWidth, const int nMapHeight,     int* pOutBuffer, const int nOutBufferSize) {     int ret = -1;      // create the map     Map map(pMap, nMapWidth, nMapHeight);      // get start and end indecies     int targetIndex = PositionToIndex(nTargetX, nTargetY, nMapWidth, nMapHeight);     int startIndex = PositionToIndex(nStartX, nStartY, nMapWidth, nMapHeight);          // if start and end are same exit     if (targetIndex == startIndex) return 0;          std::unordered_map<int, int> pathway = { {startIndex, startIndex} };     std::unordered_map<int, int> distances = { {startIndex, 0} };      // queue for indecies to process     typedef std::pair<int, int> WeightedLocation;     std::priority_queue<WeightedLocation, std::vector<WeightedLocation>, std::greater<WeightedLocation>> queue;      queue.emplace(0, startIndex);          while (!queue.empty())     {         int currentWeight, currentIndex;         std::tie(currentWeight, currentIndex) = queue.top();         queue.pop();          if (currentIndex == targetIndex)             break;          int newDistance = distances[currentIndex] + 1;         for (int n : map.GetNeighbours(currentIndex))         {             if (distances.find(n) == distances.end() || newDistance < distances[n])             {                 distances[n] = newDistance;                  int weight = newDistance + Heuristic(n % nMapWidth, n / nMapWidth, nTargetX, nTargetY);                 queue.emplace(weight, n);                 pathway[n] = currentIndex;             }         }     }      if (pathway.find(targetIndex) != pathway.end())     {         int current = targetIndex;          while (current != startIndex)         {             int outIndex = distances[current] - 1;             pOutBuffer[distances[current] - 1] = current;             current = pathway[current];         }         ret = distances[targetIndex];     }          return ret; } 

Finding the most frequent element, given that it’s Theta(n)-frequent?

We know [Ben-Or 1983] that deciding whether all elements in an array are distinct requires $ \Theta(n \log(n))$ time; and this problem reduces to finding the most frequent element, so it takes $ \Theta(n \log(n))$ time to find the most frequent element (assuming the domain of the array elements is not small).

But what happens when you know that there’s an element with frequency at least $ \alpha \cdot n$ ? Can you then decide the problem, or determine what the element is, in linear time (in $ n$ , not necessarily in $ 1/\alpha$ ) and deterministically?

Finding a boolean submatrix isomorphic to a specific set of other boolean matrices

Given a matrix $ M$ of certain size $ h\times w$ , where $ h\leq w$ , for example $ 5\times 6$ , are also given the following set $ A$ of (a)dditional matrices:

$ $ \begin{matrix} Matrices: & \begin{bmatrix} % 2 x 5 1 & 1 & 1 & 1 & 1\ 1 & 1 & 1 & 1 & 1 \end{bmatrix} & \begin{bmatrix} % 3 x 4 1 & 1 & 1 & 1\ 1 & 1 & 1 & 1\ 1 & 1 & 1 & 1 \end{bmatrix} & \begin{bmatrix} % 4 x 3 1 & 1 & 1\ 1 & 1 & 1\ 1 & 1 & 1\ 1 & 1 & 1 \end{bmatrix} & \begin{bmatrix} % 5 x 2 1 & 1\ 1 & 1\ 1 & 1\ 1 & 1\ 1 & 1 \end{bmatrix}\ Sizes: & 2 \times w – 1 & 3 \times w – 2 & 4\times w – 3 & 5\times w – 4 \end{matrix} $ $

As you can see, this specific set of matrices follows the pattern of containing only $ 1$ s, with sizes starting from $ 2\times w – 1$ up to $ h\times w – h + 1$ .

The problem is finding a submatrix of $ M$ that is isomorphic with any of the matrices in the set $ A$ . In case there is more than one solution, the result is any submatrix of maximum height first, and in case there’s again multiple candidates, any submatrix with maximum width.

The problem have the following properties:

  • $ 2 \leq h \leq w$ .
  • Each row of $ M$ has at least one $ 0$ .
  • Deduced from the way $ A$ is generated, for each $ a\in A$ of size $ a_h\times a_w$ , it happens that $ a_h + a_w – 1 = w$ .
  • The operations you can apply to $ M$ to check for homomorphism are the usual ones, you can swap rows between them, or columns betweem them, but you cannot sum or substract rows or columns between them as in lineal algebra.

I have spend already a couple of days trying to construct a polynomial-time algorithm for this problem but I don’t see it clearly. Is this problem NP-hard, taking into account all of the restrictions it has?

I’m looking for any strategy that implies to "normalize" $ M$ by applying a set of row or column swapping in a way that, in case there’s a solution, it’s in the "top left" corner of $ M$ . I have also explore the possibility of using the rank of $ M$ to see if there’s some pattern regarding its potential solution, etc. I have also try to sort the columns and rows by number of $ 1$ s and that kind of things, but my background on lineal algebra in very limited, and so it is my set of mathematical "tricks" to characterize $ M$ regarding $ A$ .

NOTE: The maximum subarray problem is similar to this one, but take notice that my best solution is not neccesarily the maximum one. If, for example, the solution submatrices of size $ 3\times 4$ and $ 5\times 2$ exists, the "best solution" is $ 5\times 2$ , because it has a bigger height, although it’s has less number of $ 1$ s.

NOTE: The graph homomorphism problem is also similar, but take notice that $ M$ is not equivalent to an adjacency matrix because it’s not square or symmetrical.

Finding a valid equation for fixed point problem

I currently am working on learning more about fixed point method. Finding equations that satisfy the constraints of a g function can sometimes require a bit of engineering. I have come across one that many would consider simple. Yet, I have been stuck on it for some time now.

Here it is $ f(x) = x^2 – x – 2 = 0 $ on $ [1.5,3]$ .

I have tried many things; however, I have yet to successfully discover one that maps domain to range for both $ g$ and $ g^\prime$ .

Would anyone be able to give me a guiding hand?

Finding the worst case running time of this piece of code?

I am working with this code:

function strange (list a[0..n-1] of integers such that abs(a[i]) ≤ n for every 0 ≤ i ≤ n - 1, list b[0..2n] of zeroes)  for i ← 0 to n - 1 do        a[i] ← a[i] + n for i ← 0 to n - 1 do        for j ← 0 to abs(a[i] - 1) do                b[j] ← b[j] + 1 return b 

I am trying to figure out the worst running time for the code above and so far I’m guessing that the first for loop will run n times, but not sure how to prove this. For the second and third for loop, I’m unsure how to approach this. If possible, could someone help me solve this?

Finding the Time Complexity – Worst Case (Big-Θ) – Array List, BST

Hi I’m a bit confused on how to find the time complexity of the following in the worst case in terms of big-Θ, I’ve figured out 1 and 2.

What is the worst-case time complexity, in terms of big-Θ, of each of these operations: (1) insert an element in the array list = Θ(1) (2) remove an element from the array list (e.g. remove an occurrence of the number 5) = Θ(n)

(3) remove the second element from the array list (i.e. the one in position 1)

(4)count the number of unique elements it contains (i.e. the number of elements excluding duplicates; e.g.[6,4,1,4,3] has 4 unique elements)

Suppose you have an initially empty array list with an underlying array of length 10. What is the length of the underlying array after:

(5) inserting 10 elements in the array list (6) inserting 10 more elements in the array list (i.e. 20 elements in total) (7) inserting 10000 more elements in the array list (i.e. 10020 elements in total)

What is the worst-case time complexity, in terms of big-Θ, of each of these operations on binary search trees: (8) add an element in the tree (assuming that the tree is balanced) (9) add an element in the tree (without assuming that the tree is balanced) (10) find the largest element in the tree (assuming that the tree is balanced) After each operation, we should still have a valid heap.

Complexity of finding a Eulerian path such that the image under a bijection is also a Eulerian path

Problem input: undirected graphs $ G$ , $ H$ and a bijection $ f: E(G) \to E(H)$
Question: Is there a Eulerian path $ p: \{1,\dots,|E(G)|\} \to E(G)$ in $ G$ such that $ f \circ p$ is a Eulerian path in $ H$ ?

Is this problem in $ P$ , $ NP$ -complete or maybe equivalent to some other well-known problem that isn’t known to be either yet?

The problem turned up as a special case of a more general problem first in the Bachelors thesis of another student last year and now in mine as well (I was improving some of the results of the other thesis). All other cases of the problem are now known to be either NP-hard or solvable in polynomial time, but neither one of us managed to make any progress on that case. On the other hand it feels like a much more "natural" problem than the other cases, so I think we may have missed a simple proof.

If undirected graphs are replaced by directed graphs in the problem statement there is a simple polynomial time algorithm (find a Eulerian path in the graph with vertex set $ V(G)\times V(H)$ and edge set $ $ \{((v_1, w_1), (v_2, w_2)) | (v_1, v_2)=e \in E(G), f(e) = (w_1, w_2)\}$ $ ignoring isolated vertices). The analogous graph for the undirected case contains 2 edges for each edge in $ G$ , so just finding a Eulerian path is no longer enough.

2D Finding an algorithm to check pizza toppings positions

Using unity 3D I am creating a 2D pizza game and I am stuck at finding an algorithm to solve this problem which is Detecting if the pizza is half and half taking into consideration that the user can put the toppings in all rotations shown in the picture and lot more possible distributions.

I used Physics2D.OverlapAreaAll to get position of ingredients on the pizza and I tried getting the sumX and sumY of coordinates of all topping A and sumX and sumY of all topping B and adding A.sumX + B.sumX and A.sumY + B.sumY and if the 2 totals are between 0 and 1 then A and B are on opposite sides but the bad distribution of toppings in the second pic is also accepted by my algorithm. The toppings must be spread like in the 1st pic

I need some easier way to detect the correct distribution of ingredients maybe using collisions or something.

if (sumX > -ErrLvl && sumX < ErrLvl && sumY > -ErrLvl && sumY < ErrLvl)               {                 Debug.Log("APPROVED HALF-HALF PIZZA");             }             else                 Debug.Log("BAD HALF-HALF PIZZA"); 

Correct distribution

Bad distribution