大厂笔试题
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
3.7 KiB

2 weeks ago
  1. /*
  2. c++
  3. N x N 沿 1 K ( K )穿:
  4. :
  5. : C/C++1000ms,:2000ms内存限制: C/C++256MB,:512MB
  6. :
  7. N K后 N N ,2N100 K2N-2 1e4
  8. :
  9. 穿
  10. 1
  11. :
  12. 2
  13. 2
  14. 1 3
  15. 2 1
  16. :2
  17. :(2)线2
  18. 2
  19. :
  20. 5
  21. 12
  22. 0 0 0 0 0
  23. 9 9 3 9 0
  24. 0 0 0 0 0
  25. 0 9 5 9 9
  26. 0 0 0 0 0
  27. :3
  28. :线:22224123
  29. K=160;K=85
  30. */
  31. #include <iostream>
  32. #include <vector>
  33. #include <queue>
  34. #include <algorithm>
  35. using namespace std;
  36. const int INF = 1e9; // 定义一个足够大的值表示不可达
  37. int N, K;
  38. vector<vector<int>> radiation;
  39. // 四个方向的移动
  40. int dx[] = {1, -1, 0, 0};
  41. int dy[] = {0, 0, 1, -1};
  42. // 判断是否可以在指定的防护能力下从 (0,0) 到 (N-1,N-1)
  43. bool canReach(int limit) {
  44. if (radiation[0][0] > limit || radiation[N-1][N-1] > limit) {
  45. return false;
  46. }
  47. vector<vector<bool>> visited(N, vector<bool>(N, false));
  48. queue<pair<int, int>> q;
  49. q.push({0, 0});
  50. visited[0][0] = true;
  51. int time = 0;
  52. while (!q.empty()) {
  53. int qsize = q.size();
  54. if (time > K) return false; // 时间超过 K
  55. while (qsize--) {
  56. int x = q.front().first;
  57. int y = q.front().second;
  58. q.pop();
  59. if (x == N-1 && y == N-1) {
  60. return true; // 成功到达终点
  61. }
  62. for (int i = 0; i < 4; ++i) {
  63. int nx = x + dx[i];
  64. int ny = y + dy[i];
  65. if (nx >= 0 && nx < N && ny >= 0 && ny < N && !visited[nx][ny] && radiation[nx][ny] <= limit) {
  66. visited[nx][ny] = true;
  67. q.push({nx, ny});
  68. }
  69. }
  70. }
  71. ++time; // 每次扩展一层,时间增加
  72. }
  73. return false; // 没有在 K 时间内到达终点
  74. }
  75. int main() {
  76. // 读入 N 和 K
  77. cin >> N >> K;
  78. radiation.resize(N, vector<int>(N));
  79. // 读入迷宫的辐射值
  80. for (int i = 0; i < N; ++i) {
  81. for (int j = 0; j < N; ++j) {
  82. cin >> radiation[i][j];
  83. }
  84. }
  85. // 二分查找防护能力
  86. int low = 0, high = 1e4, ans = INF;
  87. while (low <= high) {
  88. int mid = (low + high) / 2;
  89. if (canReach(mid)) {
  90. ans = mid;
  91. high = mid - 1;
  92. } else {
  93. low = mid + 1;
  94. }
  95. }
  96. // 输出结果
  97. cout << ans << endl;
  98. return 0;
  99. }