The task was to find the shortest path between P and K in a maze. You can move horizontally and vertically, where #
is a wall and .
is free space. I've had a lot of trouble passing on the int k
, which is the path length. I had to make a pair which contains a pair of x
and y
coordinates and int k
.
Could I have done this any better without too much change in the code, especially with the pairs and the while
loop? And how good is my code overall?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int dfs(string g[30][30], pair<int, int> p)
{
vector <pair<pair<int, int>, int> > v;
int visited[30][30] = {0};
int x, y, k = 0;
pair <pair<int, int>, int> mj;
pair <pair<int, int>, int> z;
pair <int, int> l;
z = make_pair(make_pair(p.first, p.second), 0);
v.push_back(z);
while(v.size() != 0)
{
mj = v.front();
l = mj.first;
x = l.first;
y = l.second;
k = mj.second;
v.erase(v.begin());
if(g[x][y] == "K")
return k;
if((g[x+1][y] == "." or g[x+1][y] == "K") and not(visited[x+1][y]))
{
v.push_back(make_pair(make_pair(x+1, y), k+1));
visited[x+1][y] = 1;
}
if((g[x][y+1] == "." or g[x][y+1] == "K") and not(visited[x][y+1]))
{
v.push_back(make_pair(make_pair(x, y+1), k+1));
visited[x][y+1] = 1;
}
if((g[x-1][y] == "." or g[x-1][y] == "K") and not(visited[x-1][y]))
{
v.push_back(make_pair(make_pair(x-1, y), k+1));
visited[x-1][y] = 1;
}
if((g[x][y-1] == "." or g[x][y-1] == "K") and not(visited[x][y-1]))
{
v.push_back(make_pair(make_pair(x, y-1), k+1));
visited[x][y-1] = 1;
}
}
}
int main()
{
int n, m;
pair <int, int> p;
string s, g[30][30];
cin >> n;
cin >> m;
for(int i = 0; i < n; i++)
{
cin >> s;
for(int j = 0; j < s.size(); j++)
{
g[i][j] = s.substr(j, 1);
if(g[i][j] == "P")
p = make_pair(i, j);
}
}
cout << dfs(g, p);
return 0;
}
Sample input:
6 10 ########## #.P#.....# ##.#.K#..# #..####..# #........# ##########
Sample output:
14