题目地址:http://codeforces.com/problemset/problem/374/c
用dp[i][j]代表第i行第j列的数可以走的最大距离。为-1时表示未走过,将走过但未走完的暂时标记为INF。这样假如有环的时候就返回INF了。然后用dfs搜。
代码如下:
立即学习“前端免费学习笔记(深入)”;
#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <stdlib.h>#include <math.h>#include <ctype.h>#include <queue>#include <map>#include <set>#include <algorithm>using namespace std;#define LL __int64const int INF=0x3f3f3f3f;char mp[1001][1001], str[]="DIMA";int dp[1001][1001];int jx[]={0,0,1,-1};int jy[]={1,-1,0,0};int n, m;int dfs(int x, int y, int tmp){ if(dp[x][y]!=-1) return dp[x][y]; dp[x][y]=INF; int i, a, b, t=0; tmp=(1+tmp)%4; for(i=0;i<4;i++) { a=x+jx[i]; b=y+jy[i]; if(a>=0&&a<n&&b>=0&&b<m&&mp[a][b]==str[tmp]) { t=max(t,dfs(a,b,tmp)); } } dp[x][y]=++t; return t;}int main(){ int i, j, max1=0; scanf("%d%d",&n,&m); for(i=0;i<n;i++) { scanf("%s",mp[i]); } memset(dp,-1,sizeof(dp)); for(i=0;i<n;i++) { for(j=0;j<m;j++) { if(mp[i][j]=='D') { max1=max(max1,dfs(i,j,0)); } } } if(max1/4==0) { puts("Poor Dima!"); } else if(max1>=INF) { puts("Poor Inna!"); } else printf("%d\n",max1/4); return 0;}立即学习“前端免费学习笔记(深入)”;
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号