I solved Codeforces 3A – Shortest Path of the King by reducing the board into a simple coordinate system and wrapping the logic inside a Point struct. I mapped each position into (x, y), and instead of thinking in directions directly, I focused only on how far the current point is from the target. This immediately simplified the problem into pure distance reduction on two axes.
Inside the struct, I separated the logic cleanly, one part to compute the minimum moves using max(|dx|, |dy|), and another to construct the actual path step by step. At every move, the idea stayed consistent, reduce both coordinates when possible using a diagonal move, otherwise fix one axis. What looked like an 8-direction problem collapsed into a single greedy rule, always move closer to the target in the most efficient way.
Code below!
#include <bits/stdc++.h>
using namespace std;
struct Point {
int x, y;
Point(const char *str) : x(str[0] - 'a' + 1), y(str[1] - '0') {
}
bool operator!=(const Point &p) const {
return x != p.x || y != p.y;
}
int steps(const Point &p) const {
return max(abs(x - p.x), abs(y - p.y));
}
string getDirection(const Point &p) {
string move = "";
if (x > p.x) {
move += 'L';
x--;
} else if (x < p.x) {
move += 'R';
x++;
}
if (y > p.y) {
move += 'D';
y--;
} else if (y < p.y) {
move += 'U';
y++;
}
return move;
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
char s[3], t[3];
cin >> s >> t;
Point source(s), target(t);
cout << source.steps(target) << "\n";
while (source != target) { cout << source.getDirection(target) << "\n"; }
return 0;
}







