思路:离散化之后,直接模拟就行,标记vis开三维
代码:
#include<iostream> #include<algorithm> #include<cstdio> #include<stdio.h> #include<string.h> #include<queue> #include<cmath> #include<map> #include<set> #include<vector> using namespace std; typedef long long ll; const int maxn = 1e3 + 10; const ll mod = 1e8 + 7; struct node{ ll x, y; }p[maxn]; int mp[maxn][maxn], turn_num, vis[maxn][maxn][4], nn, mm; ll x[maxn], y[maxn]; int dir[4][2] = {1, 0, 0, -1, -1, 0, 0, 1}; //下,左,上,右 bool dfs(int xx, int yy, int turn){ //将要朝向turn if(vis[xx][yy][turn]) return false; vis[xx][yy][turn] = 1; int xxx = xx + dir[turn][0], yyy = yy + dir[turn][1]; if(xxx < 0 || xxx > nn - 1 || yyy < 0 || yyy > mm - 1) return true; while(mp[xxx][yyy] != 1){ if(vis[xxx][yyy][turn]) return false; vis[xxx][yyy][turn] = 1; xxx += dir[turn][0]; yyy += dir[turn][1]; if(xxx < 0 || xxx > nn - 1 || yyy < 0 || yyy > mm - 1) return true; } turn_num++; return dfs(xxx - dir[turn][0], yyy - dir[turn][1], (turn + 1) % 4); } int main(){ int n, sx, sy; while(scanf("%d", &n) != EOF){ turn_num = 0; memset(mp, 0, sizeof(mp)); memset(vis, 0, sizeof(vis)); for(int i = 0; i < n; i++){ scanf("%lld%lld", &p[i].x, &p[i].y); x[i] = p[i].x; y[i] = p[i].y; } x[n] = 0, y[n] = 0, p[n].x = 0, p[n].y = 0; n++; sort(x, x + n); sort(y, y + n); int num1 = unique(x, x + n) - x; int num2 = unique(y, y + n) - y; for(int i = 0; i < n; i++){ int X, Y; X = lower_bound(x, x + num1, p[i].x) - x; Y = lower_bound(y, y + num2, p[i].y) - y; if(p[i].x == 0 && p[i].y == 0){ sx = X, sy = Y; } else{ mp[X][Y] = 1; } } nn = num1, mm = num2; bool flag = dfs(sx, sy, 0); if(flag) printf("%d\n", turn_num); else printf("-1\n"); } return 0; } /* 4 1 0 0 1 0 -1 -1 0 */
原文地址:https://www.cnblogs.com/KirinSB/p/9891020.html
时间: 2024-10-03 19:46:59