跳到正文

算法·理论

核桃 P1185无限大平面 题解

wujiawei36约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年8月14日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

题意

问能否从起点走到无限远,同时统计在无限图中能经过的点在原图中能到多少个不同的点。

解析

考虑从起点开始BFS,普通的搜索的vis数组只标记 (i,j)(i,j) 点是否走过,在这里我们用vis数组标记 (i,j)(i,j) 在哪一个地图被走过。 如果现在走到了有标记的 (i,j)(i,j),且这个标记不是在当前地图中走到的,那么说明可以从一个地图的 (i,j)(i,j) 走到另一个地图的 (i,j)(i,j),则可以一直走。 不同道具个数的话把各个地图的vis重叠起来看有没有走过就行了。

标程

C++
.include<bits/stdc++.h>
.define pii pair<int,int>
.define allof(o) (o).begin(),(o).end()
.define lowbit(x) ((x)&(-(x)))
.sing namespace std;
.nt gox[]={-1,1,0,0};
.nt goy[]={0,0,-1,1};
.nt vis[1505][1505];
.har a[1505][1505];
.ap<pii,int> mp;
.ool can_inf=0;
.ueue<pii> q;
.nt n,m,p=0;
.nt get_val(int x,int y)
.
.x--,y--;
.int xx=(x-(x%n+n)%n)/n;
.int yy=(y-(y%m+m)%m)/m;
.int res=0;
.if(mp.count({xx,yy}))res=mp[{xx,yy}];
.else res=(mp.insert({{xx,yy},++p}),p);
.return res;
.
.oid BFS(int stx,int sty)
.
.vis[stx][sty]=get_val(stx,sty);
.q.push({stx,sty});
.while(q.size())
.{
.	int x=q.front().first,y=q.front().second;q.pop();
.	for(int k=0;k<4;k++)
.	{
.		int xx=x+gox[k],yy=y+goy[k];
.		if(a[((xx-1)%n+n)%n+1][((yy-1)%m+m)%m+1]!='#')
.		{
.			if(vis[((xx-1)%n+n)%n+1][((yy-1)%m+m)%m+1]&&vis[((xx-1)%n+n)%n+1][((yy-1)%m+m)%m+1]!=get_val(xx,yy))
.				can_inf=1;
.			if(!vis[((xx-1)%n+n)%n+1][((yy-1)%m+m)%m+1])
.			{
.				vis[((xx-1)%n+n)%n+1][((yy-1)%m+m)%m+1]=get_val(xx,yy);
.				q.push({xx,yy});
.			}
.		}
.	}
.}
.
.igned main()
.
.ios::sync_with_stdio(false);
.cin.tie(0);cout.tie(0);
.cin>>n>>m;
.int stx=0,sty=0;
.for(int i=1;i<=n;i++)
.	for(int j=1;j<=m;j++)
.		cin>>a[i][j];
.cin>>stx>>sty;
.
.can_inf=0;
.memset(vis,0,sizeof(vis));
.
.BFS(stx,sty);
.if(can_inf)cout<<"Yes\n";
.else cout<<"No\n";
.int cnt=0;
.for(int i=1;i<=n;i++)
.	for(int j=1;j<=m;j++)
.		if(vis[i][j])cnt++;
.cout<<cnt;
.return 0;
.

后记

来都来了,点个赞呗。

原文