http://hihocoder.com/problemset/problem/1519?sid=1167472
要求拐弯最小次数,并且只有碰到墙或者碰到地图边界才能拐弯。
bfs,每次入队的点是当前点往各方向一条道走到黑时候的点。
注意这种情况:
5 5
S#…
…..
..T..
…..
…..
判断到没到终点要每走一步就判断,否则会误判上面的情况。
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <unordered_map>
#include <algorithm>
#include <stdio.h>
#include <string.h>
using namespace std;
char board[505][505];
int n, m;
int r, c;
int dx[4] = { 0, 0, 1, -1 };
int dy[4] = { 1, -1, 0, 0 };
bool visited[505][505][4];
struct point {
int x, y, s;
int d;
point() {}
point(int _x, int _y, int _s, int _d) : x(_x), y(_y), s(_s), d(_d) {}
};
bool valid(int x, int y) {
if (x < 0 || x >= n || y < 0 || y >= m || board[x][y] == '#') {
return false;
}
return true;
}
int bfs(int x, int y) {
queue<point> Q;
for (int i = 0; i < 4; ++i) {
int next_x = x, next_y = y;
while (valid(next_x + dx[i], next_y + dy[i])) {
next_x += dx[i];
next_y += dy[i];
if (board[next_x][next_y] == 'T') {
return 0;
}
}
visited[next_x][next_y][i] = true;
Q.push(point(next_x, next_y, 0, i));
}
while (!Q.empty()) {
point cur = Q.front();
Q.pop();
//cout << " x " << cur.x << " y " << cur.y << " d " << cur.d << endl;
if (board[cur.x][cur.y] == 'T') {
return cur.s;
}
for (int i = 0; i < 4; ++i) {
int next_x = cur.x, next_y = cur.y;
while (valid(next_x + dx[i], next_y + dy[i])) {
next_x += dx[i];
next_y += dy[i];
if (board[next_x][next_y] == 'T') {
return cur.s + 1;
}
}
if (!visited[next_x][next_y][i]) {
visited[next_x][next_y][i] = true;
Q.push(point(next_x, next_y, cur.s + 1, i));
}
}
}
return -1;
}
int main() {
while (cin >> n >> m) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> board[i][j];
if (board[i][j] == 'S') {
r = i;
c = j;
}
}
}
memset(visited, false, sizeof(visited));
int ans = bfs(r, c);
cout << ans << endl;
}
return 0;
}