问题 I: Maze Master
时间限制: 1 Sec 内存限制: 128 MB
题目描述
Takahashi has a maze, which is a grid of H×W squares with H horizontal rows and W vertical columns.
The square at the i-th row from the top and the j-th column is a “wall” square if Sij is ‘#’, and a “road” square if Sij is ‘.’.
From a road square, you can move to a horizontally or vertically adjacent road square.
You cannot move out of the maze, move to a wall square, or move diagonally.
Takahashi will choose a starting square and a goal square, which can be any road squares, and give the maze to Aoki.
Aoki will then travel from the starting square to the goal square, in the minimum number of moves required.
In this situation, find the maximum possible number of moves Aoki has to make.
Constraints
·1≤H,W≤20
·Sij is ‘.’ or ‘#’.
·S contains at least two occurrences of ‘.’.
Any road square can be reached from any road square in zero or more moves.
输入
Input is given from Standard Input in the following format:
H W
S11…S1W
:
SH1…SHW
输出
Print the maximum possible number of moves Aoki has to make.
样例输入 Copy
【样例1】
3 3
...
...
...
【样例2】
3 5
...#.
.#.#.
.#...
样例输出 Copy
【样例1】
4
【样例2】
10
提示
样例1解释
If Takahashi chooses the top-left square as the starting square and the bottom-right square as the goal square, Aoki has to make four moves.
样例2解释
If Takahashi chooses the bottom-left square as the starting square and the top-right square as the goal square, Aoki has to make ten moves.
AC
#include<bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)n;i++)
#define rep1(i,n) for(int i=1;i<=(int)n;i++)
#define redp(i,n) for(int i=(int)n-1;i>=0;i--)
#define redp1(i,n) for(int i=(int)n;i>=1;i--)
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int dx[] = { 0, 1, -1, 0, 1, -1, 1, -1 };
const int dy[] = { 1, 0, 0, -1, 1, -1, -1, 1 };
const int MOD = 1e9 + 7;
const int INF=0x3f3f3f3f;
bool flag=true;
//----------------------------------------------
const int N=1e3+5;
//----------------------------------------------
int maze[30][30],p[30][30];
void bfs(int i,int j,int n)
{
if((maze[i][j])&&(p[i][j]>n||p[i][j]==-1))
{
p[i][j]=n;
bfs(i+1,j,n+1);
bfs(i,j+1,n+1);
bfs(i-1,j,n+1);
bfs(i,j-1,n+1);
}
}
//----------------------------------------------
int main()
{
int n,m=0,i,j,k,l=0,x,y,ans=0;
ll cnt=0;
char a;
scanf("%d %d",&n,&m);
getchar();
rep1(i,n)
{
rep1(j,m)
{
scanf("%c",&a);
maze[i][j]=(a=='.');
}
getchar();
}
rep1(i,n)rep1(j,m)
{
memset(p,-1,sizeof(p));
bfs(i,j,0);
l=0;
rep1(x,n)rep1(y,m)l=max(l,p[x][y]);
ans=max(ans,l);
}
printf("%d",ans);
return 0;
}