Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <queue>
- using namespace std;
- const int inf = 100;
- struct kletka
- {
- int x, y, cost;
- void new_kletka(int x, int y, int cost)
- {
- this->x = x;
- this->y = y;
- this->cost = cost;
- }
- void print_kletka()
- {
- cout << x+1 << " " << y+1 << endl;
- }
- };
- class Graph
- {
- queue<kletka> Q;
- int n, m, *dx, *dy, limit;
- bool **arr;
- kletka *path, start;
- public:
- Graph(int x, int a)
- {
- n = x;
- m = a;
- limit = n*m-1;
- dx = new int[8]{2, 1, -2, -1, 1, -1, 2, -2};
- dy = new int[8]{-1, -2, 1, 2, 2, -2, 1, -1};
- arr = new bool*[n]{0};
- for (int i = 0; i < n; i++)
- arr[i] = new bool[m]{0};
- arr[0][0] = true;
- start.new_kletka(0, 0, 0);
- path = new kletka[limit];
- }
- void poisk_path();
- int poisk_min (kletka *watched);
- void get_result();
- int variant(kletka a);
- void get_arr();
- };
- int Graph::variant(kletka a)
- {
- int x = 0;
- if(a.x >= 0 && a.x < n && a.y >= 0 && a.y < m && arr[a.x][a.y] == 0)
- x++;
- return x;
- }
- int Graph::poisk_min ( kletka *watched)
- {
- int min = inf, result = -1;
- for (int i = 0; i < 8; i++)
- if (watched[i].cost <= min && watched[i].cost > -1)
- {
- min = watched[i].cost;
- result = i;
- }
- return result;
- }
- void Graph::poisk_path()
- {
- int shet = 0;
- Q.push(start);
- while (shet != limit && !Q.empty())
- {
- kletka current = Q.front();
- Q.pop();
- kletka *visited = new kletka[8];
- for (int i = 0; i < 8; i++)
- {
- kletka check;
- check.new_kletka (current.x + dx[i], current.y + dy[i], -1);
- if (variant(check))
- {
- check.cost = 0;
- for (int p = 0; p < 8; p++)
- {
- kletka possible_path;
- possible_path.new_kletka(check.x + dx[p], check.y + dy[p], -1);
- check.cost += variant(possible_path);
- }
- }
- visited[i] = check;
- }
- int index = poisk_min(visited);
- if (index != -1)
- {
- kletka a = visited[index];
- arr[a.x][a.y] = 1;
- path[shet] = a;
- shet++;
- Q.push(a);
- }
- }
- if (shet != limit)
- cout << -1;
- else get_result();
- }
- void Graph::get_result()
- {
- start.print_kletka();
- for (int i = 0; i < limit; i++)
- path[i].print_kletka();
- }
- void Graph::get_arr()
- {
- for (int i= 0; i < n; i++)
- {
- for (int j = 0; j < m; j++)
- {
- cout.width(3);
- cout << arr[i][j] << " ";
- }
- cout << endl;
- }
- }
- int main()
- {
- int n, m;
- cin >> n >> m;
- Graph object(n, m);
- object.poisk_path();
- }
Add Comment
Please, Sign In to add comment