1. 程式人生 > 其它 >【ybt高效進階1-5-1】走迷宮

【ybt高效進階1-5-1】走迷宮

技術標籤:# dfs或bfsbfs

走迷宮

題目連結:ybt高效進階1-5-1

題目大意

在一個 N×N 的地圖中,一些地方可以走一些不可以走。
問你從一個地方走到另一個地方的最小步數。

思路

就是直接 bfs 搞過去。

跑圖,跑到要的點就輸出退出。

程式碼

#include<queue>
#include<cstdio>

using namespace std;

int n, a[1001][1001], sx, sy, tx, ty, ans, now, nowdis, nowx, nowy;
int dx[4] = {0, 1, 0, -1}, dy[
4] = {1, 0, -1, 0}; queue <pair<int, int> > q; bool in[1001][1001]; char c; int get_num(int x, int y) { return (x - 1) * n + y - 1; } bool ch(int x, int y) { if (x < 1 || x > n) return 0; if (y < 1 || y > n) return 0; return 1; } void bfs() { q.push(make_pair(get_num(sx, sy),
0)); in[sx][sy] = 1; while (!q.empty()) { nowx = q.front().first / n + 1; nowy = q.front().first % n + 1; nowdis = q.front().second; q.pop(); for (int i = 0; i < 4; i++) if (ch(nowx + dx[i], nowy + dy[i]) && !a[nowx + dx[i]][nowy + dy[i]] && !in[nowx + dx[i]][nowy +
dy[i]]) { in[nowx + dx[i]][nowy + dy[i]] = 1; if (tx == nowx + dx[i] && ty == nowy + dy[i]) { ans = nowdis + 1; return ; } q.push(make_pair(get_num(nowx + dx[i], nowy + dy[i]), nowdis + 1)); } } } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { c = getchar(); while (c != '0' && c != '1') c = getchar(); a[i][j] = c - '0'; } } scanf("%d %d %d %d", &sx, &sy, &tx, &ty); bfs(); printf("%d", ans); return 0; }