1+ #include < iostream>
2+ #include < queue>
3+ #include < vector>
4+ using namespace std ;
5+
6+ const int N = 500 ;
7+ int n, m;
8+ bool arr[N][N];
9+ int dxf[] = { -1 , 1 , -1 , 0 , 0 , 1 };
10+ int dyf[] = { -1 , 1 , 0 , -1 , 1 , 0 };
11+ int dxt[] = { -1 , 1 , -1 , 0 , 0 , 1 };
12+ int dyt[] = { 1 , -1 , 0 , -1 , 1 , 0 };
13+ struct Pos {
14+ int cx, cy, ct;
15+ bool cf;
16+ bool operator <(const Pos& other) const {
17+ return ct > other.ct ;
18+ }
19+ };
20+
21+ int dijkstra () {
22+ priority_queue<Pos> pq;
23+ pq.push ({ 0 , 0 , arr[0 ][0 ], false });
24+ vector<vector<vector<int >>> dist (2 , vector<vector<int >>(n, vector<int >(m, 2e9 )));
25+ dist[0 ][0 ][0 ] = arr[0 ][0 ];
26+
27+ while (!pq.empty ()) {
28+ auto [cx, cy, ct, cf] = pq.top (); pq.pop ();
29+
30+ if (dist[cf][cx][cy] < ct) continue ;
31+ // cout << cx << " " << cy << " " << ct << " " << cf << "\n";
32+ if (cx == n - 1 && cy == m - 1 && !cf) return ct;
33+
34+ if (!cf) {
35+ for (int i = 0 ; i < 6 ; ++i) {
36+ int nx = cx + dxf[i], ny = cy + dyf[i];
37+
38+ if (0 <= nx && nx < n && 0 <= ny && ny < m) {
39+ int nt = ct;
40+ if (i < 2 && arr[nx][ny] != cf) ++nt;
41+ if (i >= 2 && arr[nx][ny] == cf) ++nt;
42+ bool nf = (ct == nt ? arr[nx][ny] : !arr[nx][ny]);
43+
44+ if (dist[nf][nx][ny] > nt) {
45+ dist[nf][nx][ny] = nt;
46+ pq.push ({ nx, ny, nt, nf });
47+ }
48+ }
49+ }
50+ }
51+ else {
52+ for (int i = 0 ; i < 6 ; ++i) {
53+ int nx = cx + dxt[i], ny = cy + dyt[i];
54+
55+ if (0 <= nx && nx < n && 0 <= ny && ny < m) {
56+ int nt = ct;
57+ if (i < 2 && arr[nx][ny] != cf) ++nt;
58+ if (i >= 2 && arr[nx][ny] == cf) ++nt;
59+ bool nd = (ct == nt ? arr[nx][ny] : !arr[nx][ny]);
60+
61+ if (dist[nd][nx][ny] > nt) {
62+ dist[nd][nx][ny] = nt;
63+ pq.push ({ nx, ny, nt, nd });
64+ }
65+ }
66+ }
67+ }
68+ }
69+ return -1 ;
70+ }
71+
72+ int main () {
73+ ios::sync_with_stdio (0 );
74+ cin.tie (0 );
75+
76+ cin >> n >> m;
77+ for (int i = 0 ; i < n; ++i) {
78+ for (int j = 0 ; j < m; ++j) {
79+ char c; cin >> c;
80+ arr[i][j] = (c == ' /' ? true : false );
81+ }
82+ }
83+
84+ int res = dijkstra ();
85+ if (res == -1 ) cout << " NO SOLUTION" ;
86+ else cout << res;
87+ }
0 commit comments