C++
$\color{gold}{— > 蓝桥杯辅导课题解}$
法一:
思路:
模拟
$矩阵行号和列号从0开始$
$图解:$
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int w, m, n;
int main() {
cin >> w >> m >> n;
m --, n --;
int x1 = m / w, y1 = m % w;
int x2 = n / w, y2 = n % w;
if (x1 % 2) y1 = w - 1 - y1;
if (x2 % 2) y2 = w - 1 - y2;
cout << abs(x1 - x2) + abs(y1 - y2);
return 0;
}
法二:
思路:
模拟
$矩阵行号和列号从1开始$
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int w, m, n;
int x1, y1, x2, y2;
int main() {
cin >> w >> m >> n;
x1 = m / w, y1 = m % w;
x2 = n / w, y2 = n % w;
if (m % w) x1 ++;
if (n % w) x2 ++;
if (m % w == 0) y1 += w;
if (n % w == 0) y2 += w;
if (x1 % 2 == 0) y1 = (w - y1 + 1) % w;
if (x2 % 2 == 0) y2 = (w - y2 + 1) % w;
cout << abs(x1 - x2) + abs(y1 - y2);
return 0;
}