1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| int m, n; bool isFound = false; int minCnt = INT_MAX;
void findShortestPath(const vector<vector<bool> >& map, vector<vector<bool> >& visited, int curX, int curY, int cnt) { if (curX == n - 1 || curY == m - 1) { isFound = true; if (cnt < minCnt) minCnt = cnt; return; } if (curX < n - 1 && !barrier[curX + 1][curY] && !visited[curX + 1][curY]) { visited[curX + 1][curY] = true; shortestPath(barrier, visited, curX + 1, curY, cnt + 1); visited[curX + 1][curY] = false; } if (curY < m - 1 && !barrier[curX][curY + 1] && !visited[curX][curY + 1]) { visited[curX][curY + 1] = true; shortestPath(barrier, visited, curX, curY + 1, cnt + 1); visited[curX][curY + 1] = false; } if (curX > 0 && !barrier[curX - 1][curY] && !visited[curX - 1][curY]) { visited[curX - 1][curY] = true; shortestPath(barrier, visited, curX - 1, curY, cnt + 1); visited[curX - 1][curY] = false; } if (curY > 0 && !barrier[curX][curY - 1] && !visited[curX][curY - 1]) { visited[curX][curY - 1] = true; shortestPath(barrier, visited, curX, curY - 1, cnt + 1); visited[curX][curY - 1] = false; } }
int main() { int k; cin >> n >> m >> k; vector<vector<bool> > barrier(n, vector<bool>(n, false)); vector<vector<bool> > visited(n, vector<bool>(n, false)); for (int i = 0; i < k; ++i) { int x, y; cin >> x >> y; barrier[x][y] = true; } shortestPath(barrier, visited, 0, 0, 0); if (isFound) cout << minCnt << endl; else cout << 0 << endl; }
|