[BFS]A. 【例题1】走迷宫
A . 【 例 题 1 】 走 迷 宫
解析
简单的BFS模板题
Code
#include <bits/stdc++.h> #define N 1005 using namespace std; const int dx[5] = {0, 1, -1, 0, 0}; const int dy[5] = {0, 0, 0, 1, -1}; int n, sx, sy, tx, ty; int st[N * N][4], a[N][N], f[N][N]; int check (int x, int y) { if (x <= n && y <= n && x >= 1 && y >= 1) return 1; return 0; } void bfs (int x, int y) { int tail = 1, head = 0; st[1][1] = x; st[1][2] = y; st[1][3] = 0; f[x][y] = 1; while (head < tail) { head ++; for (int i = 1; i <= 4; ++ i) { int ex = st[head][1] + dx[i]; int ey = st[head][2] + dy[i]; if (check (ex, ey)) if (!a[ex][ey] && !f[ex][ey]) { tail ++; f[ex][ey] = 1; st[tail][1] = ex; st[tail][2] = ey; st[tail][3] = st[head][3] + 1; if (ex == tx && ey == ty) { printf ("%d", st[tail][3]); return ; } } } } } int main () { scanf ("%d", &n); for (int i = 1; i <= n; ++ i) for (int j = 1; j <= n; ++ j) scanf ("%1d", &a[i][j]); scanf ("%d%d%d%d", &sx, &sy, &tx, &ty); bfs (sx, sy); return 0; }