Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <assert.h>
- #include <limits.h>
- #include <iostream>
- using namespace std;
- #include <queue>
- #include <math.h>
- typedef struct t_cell {
- int x;
- int y;
- double distance;
- bool operator>(const t_cell &rhs) const {
- return (distance > rhs.distance);
- }
- } cell;
- typedef priority_queue<cell, vector<cell>, greater<cell>> workqueue;
- char **G;
- int H, W;
- int **distances;
- double heur(int x1, int y1, int x2, int y2) {
- return (
- sqrt((x1 - x2)*(x1 - x2) + (y1 - y2) * (y1 - y2))
- );
- }
- bool is_free(int x, int y) {
- if (x < 0 || y < 0) return false;
- if (x >= W || y >= H) return false;
- if (G[y][x] == '#') return false;
- //cout << "is_free (" << x << ", " << y << "): true" << endl;
- return true;
- }
- void check_n_add(workqueue &q, int x, int y) {
- if (is_free(x, y)) {
- double dist = heur(W-1, H-1, x, y);
- if (distances[y][x] > dist) {
- //cout << "Updating distance" << endl;
- distances[y][x] = dist;
- }
- else {
- return;
- }
- //cout << "Added: " << x << ", " << y << ", " << dist << endl;
- q.push({x, y, dist});
- }
- }
- int jump(int H, int W, char** G) {
- ::H = H;
- ::W = W;
- ::G = G;
- distances = new int*[H];
- for (int i = 0; i < H; i++) distances[i] = new int[W];
- for (int i = 0; i < H; i++)
- for (int j = 0; j < W; j++) {
- distances[i][j] = INT_MAX;
- }
- int px, py;
- px = py = 0;
- int steps = 0;
- workqueue q;
- q.push({0, 0, INT_MAX});
- while (q.size() > 0) {
- cell nearest = q.top(); q.pop();
- px = nearest.x;
- py = nearest.y;
- //cout << "moving to: " << px << ", " << py << ", " << nearest.distance << endl;
- if (px == W-1 && py == H-1) {
- //cout << "Found" << endl;
- break;
- }
- steps++;
- check_n_add(q, px+1, py);
- check_n_add(q, px+2, py);
- check_n_add(q, px, py+1);
- check_n_add(q, px, py+2);
- check_n_add(q, px-1, py);
- check_n_add(q, px-2, py);
- check_n_add(q, px, py-1);
- check_n_add(q, px, py-2);
- check_n_add(q, px+1, py+1);
- check_n_add(q, px-1, py-1);
- check_n_add(q, px-1, py+1);
- check_n_add(q, px+1, py-1);
- }
- //cout << "Steps: " << steps << endl;
- return steps;
- }
- int main() {
- FILE *fr, *fw;
- int H, W, i;
- char** G;
- fr = fopen("input.txt", "r");
- fw = fopen("output.txt", "w");
- assert(2 == fscanf(fr, "%d%d", &H, &W));
- G = (char**) malloc(H * sizeof(char*));
- for(i=0; i<H; i++) {
- G[i] = (char*) malloc(W * sizeof(char*));
- assert(1 == fscanf(fr, "%s", G[i]));
- }
- fprintf(fw, "%d\n", jump(H, W, G));
- fclose(fr);
- fclose(fw);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment