90 lines
2.6 KiB
C++
90 lines
2.6 KiB
C++
#include <fstream>
|
|
#include <iostream>
|
|
#include <list>
|
|
#include <vector>
|
|
|
|
enum GRID_STATUS { GRID_CLEAR, GRID_BLOCKED };
|
|
|
|
class Point {
|
|
public:
|
|
Point(int x0, int y0) : x(x0), y(y0) {}
|
|
int x, y;
|
|
};
|
|
|
|
void read_grid(std::istream& istr, std::vector<std::vector<GRID_STATUS>>& blocked_grid, int& start_x, int& start_y) {
|
|
int x, y;
|
|
int max_x = 0, max_y = 0;
|
|
std::list<Point> blocked_points;
|
|
while ((istr >> x >> y) && !(x == 0 && y == 0)) {
|
|
blocked_points.push_back(Point(x, y));
|
|
if (x > max_x) max_x = x;
|
|
if (y > max_y) max_y = y;
|
|
}
|
|
|
|
istr >> start_x >> start_y;
|
|
if (start_x > max_x) max_x = start_x;
|
|
if (start_y > max_y) max_y = start_y;
|
|
|
|
std::vector<GRID_STATUS> one_row_of_ys(max_y + 1, GRID_CLEAR);
|
|
std::vector<std::vector<GRID_STATUS>> empty_grid(max_x + 1, one_row_of_ys);
|
|
blocked_grid = empty_grid;
|
|
|
|
for (Point& p : blocked_points) {
|
|
blocked_grid[p.x][p.y] = GRID_BLOCKED;
|
|
}
|
|
}
|
|
|
|
void print_grid(const std::vector<std::vector<GRID_STATUS>>& blocked_grid, unsigned int start_x, unsigned int start_y) {
|
|
std::cout << "Grid visualization:\n";
|
|
for (unsigned int y = 0; y < blocked_grid[0].size(); ++y) {
|
|
for (unsigned int x = 0; x < blocked_grid.size(); ++x) {
|
|
if (x == start_x && y == start_y)
|
|
std::cout << " S";
|
|
else if (blocked_grid[x][y] == GRID_BLOCKED)
|
|
std::cout << " X";
|
|
else
|
|
std::cout << " .";
|
|
}
|
|
std::cout << std::endl;
|
|
}
|
|
}
|
|
|
|
int countPaths(int x, int y, const std::vector<std::vector<GRID_STATUS>>& blocked_grid) {
|
|
// Base case: if we are at the origin, there is 1 path
|
|
if (x == 0 && y == 0) return 1;
|
|
|
|
// If the current cell is blocked, return 0
|
|
if (blocked_grid[x][y] == GRID_BLOCKED) return 0;
|
|
|
|
int paths = 0;
|
|
|
|
// Move left if x > 0
|
|
if (x > 0) paths += countPaths(x - 1, y, blocked_grid);
|
|
|
|
// Move up if y > 0
|
|
if (y > 0) paths += countPaths(x, y - 1, blocked_grid);
|
|
|
|
return paths;
|
|
}
|
|
|
|
int main(int argc, char* argv[]) {
|
|
if (argc != 2) {
|
|
std::cerr << "Usage: " << argv[0] << " grid-file" << std::endl;
|
|
return 1;
|
|
}
|
|
std::ifstream istr(argv[1]);
|
|
if (!istr) {
|
|
std::cerr << "Could not open " << argv[1] << std::endl;
|
|
return 1;
|
|
}
|
|
|
|
std::vector<std::vector<GRID_STATUS>> blocked_grid;
|
|
int start_x, start_y;
|
|
read_grid(istr, blocked_grid, start_x, start_y);
|
|
print_grid(blocked_grid, start_x, start_y);
|
|
|
|
int result = countPaths(start_x, start_y, blocked_grid);
|
|
std::cout << "Number of legal paths to the origin: " << result << std::endl;
|
|
return 0;
|
|
}
|