Homework New
This commit is contained in:
73
Exercise/Homework6/BFS.cpp
Normal file
73
Exercise/Homework6/BFS.cpp
Normal file
@@ -0,0 +1,73 @@
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <queue>
|
||||
#include <tuple>
|
||||
using namespace std;
|
||||
|
||||
int startx, starty, endx, endy;
|
||||
vector<vector<int>> map;
|
||||
vector<vector<bool>> visited;
|
||||
int n, m, t;
|
||||
|
||||
int dx[] = {0, 0, 1, -1};
|
||||
int dy[] = {1, -1, 0, 0};
|
||||
int ans = 1145141919;
|
||||
|
||||
bool isvalid(int x, int y) {
|
||||
return x >= 0 && x < n && y >= 0 && y < m && map[x][y] != 1 && !visited[x][y];
|
||||
}
|
||||
|
||||
int bfs(int startx, int starty){
|
||||
queue<tuple<int, int, int>> q;
|
||||
q.push(make_tuple(startx, starty, 0));
|
||||
visited[startx][starty] = true;
|
||||
while (!q.empty()) {
|
||||
int x = get<0>(q.front());
|
||||
int y = get<1>(q.front());
|
||||
int step = get<2>(q.front());
|
||||
q.pop();
|
||||
if (x == endx && y == endy) {
|
||||
return step;
|
||||
}
|
||||
for (int i = 0; i < 4; i++) {
|
||||
int nx = x + dx[i];
|
||||
int ny = y + dy[i];
|
||||
if (isvalid(nx, ny)) {
|
||||
q.push(make_tuple(nx, ny, step + 1));
|
||||
visited[nx][ny] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 1145141919;
|
||||
}
|
||||
|
||||
int main(){
|
||||
while (cin >> n >> m >> t) {
|
||||
map.assign(n, vector<int>(m));
|
||||
visited.assign(n, vector<bool>(m, false));
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < m; j++) {
|
||||
cin >> map[i][j];
|
||||
if (map[i][j] == 3) {
|
||||
startx = i;
|
||||
starty = j;
|
||||
}
|
||||
if (map[i][j] == 4) {
|
||||
endx = i;
|
||||
endy = j;
|
||||
}
|
||||
}
|
||||
}
|
||||
visited[startx][starty] = true;
|
||||
ans = bfs(startx, starty);
|
||||
if (ans == 1145141919) {
|
||||
cout << "can not save" << endl;
|
||||
continue;
|
||||
}
|
||||
int maxs = min(t, ans);
|
||||
int saved = maxs > 0 ? maxs - 1 : 0;
|
||||
cout << ans - saved << endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user