The Crystal Maze
Time Limit: 2000 ms Case Time Limit: 2000 ms Memory Limit: 32768 KB
Submit: 8 Accepted: 2
Description
You are in a plane and you are about to be dropped with a parasuit in a crystal maze. As the name suggests, the maze is full of crystals. Your task is to collect as many crystals as possible.
To be more exact, the maze can be modeled as an M x N 2D grid whereM denotes the number of rows andN denotes the number of columns. There are three types of cells in the grid:
1. A '#' denotes a wall, you may not pass through it.
2. A 'C' denotes a crystal. You may move through the cell.
3. A '.' denotes an empty cell. You may move through the cell.
Now you are given the map of the maze, you want to find where to land such that you can collect maximum number of crystals. So, you are spotting some positionx, y and you want to find the maximum number of crystals you may get if you land to cell(x, y). And you can only move vertically or horizontally, but you cannot pass through walls, or you cannot get outside the maze.
Input
Input starts with an integer T (≤ 10), denoting the number of test cases.
Each case starts with a line containing three integers M, N and Q (2 ≤ M, N ≤ 500, 1 ≤ Q ≤ 1000). Each of the nextM lines containsN characters denoting the maze. You can assume that the maze follows the above restrictions.
Each of the next Q lines contains two integers xi andyi (1 ≤ xi ≤ M, 1 ≤ yi ≤ N) denoting the cell where you want to land. You can assume that cell(xi, yi) is empty i.e. the cell contains '.'.
Output
For each case, print the case number in a single line. Then print Q lines, where each line should contain the maximum number of crystals you may collect if you land on cell(xi, yi).
Sample Input
Sample Input | Output for Sample Input |
1 4 5 2 ..#.. .C#C. ##..# ..C#C 1 1 4 1 | Case 1: 1 2 |
Sample Output
分析:
把算过的答案存起来,放在数组data【】里,这题 500*500 的图,最多 1000 次询问,大家注意 TLE……很好的题目
代码:
#include <cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#define maxn 505
using namespace std;
bool visit[maxn][maxn];
char map[maxn][maxn];
int data[maxn][maxn],stack[maxn][maxn],sta[maxn][maxn];
int dir[4][2] = {{0,-1},{0,1},{1,0},{-1,0}};
int q,p,ans,dd;
void dfs(int x,int y)
{
int i,j,nx,ny;
visit[x][y]=1;
if(map[x][y]=='C')
ans++;
for(i=0;i<4;i++)
{
nx=x+dir[i][0];
ny=y+dir[i][1];
if(nx>=0&&nx<p&&ny>=0&&ny<q&&map[nx][ny]!='#'&&!visit[nx][ny])
{
if(map[nx][ny]=='.')
{
sta[nx][ny]=1;
}
dfs(nx,ny);
}
}
}
int main()
{
int i,j,cas=1,t,que,x,y,k;
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&p,&q,&que);
for(i=0;i<p;i++)
for(j=0;j<q;j++)
cin>>map[i][j];
getchar();//getchar();
memset(data,-1,sizeof(data));
printf("Case %d:\n",cas++);
for(i=0;i<que;i++)
{
scanf("%d%d",&x,&y);
x--;y--;
if(map[x][y]=='.'&&data[x][y]==-1)
{
memset(sta,-1,sizeof(sta));
memset(visit,0,sizeof(visit));
ans=0;
sta[x][y]=1;
dfs(x,y);
for(int k=0;k<p;k++)
for(int u=0;u<q;u++)
if(sta[k][u]==1)
{
data[k][u]=ans;
}
}
printf("%d\n",data[x][y]);
}
}
return 0;
}