LightOJ 1337 F - The Crystal Maze (bfs)

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 where M denotes the number of rows and N denotes the number of columns. There are three types of cells in the grid:

  1. '#' denotes a wall, you may not pass through it.
  2. 'C' denotes a crystal. You may move through the cell.
  3. '.' 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 position x, 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 Mand Q (2 ≤ M, N ≤ 500, 1 ≤ Q ≤ 1000). Each of the next M lines contains N characters denoting the maze. You can assume that the maze follows the above restrictions.

Each of the next Q lines contains two integers xi and yi (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

1

4 5 2

..#..

.C#C.

##..#

..C#C

1 1

4 1

Sample Output

Case 1:

1

2

//解题思路:看这道题的输入会发现容易超时,第一反应就是需要记忆化搜索,我选择用 bfs 来寻找这一片连通区域,以及水晶的数量 cnt;

//是连通区域的点用相同的 flag 进行标记,每一个不同的 flag 都对应唯一一个 cnt ;

//在每次输入时都要看是否 visit

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <queue>
#include <cstring> using namespace std;
int n,m,q,xi,yi,t;
char data[][];
int visit[][],map[];
int to[][]={{,},{,-},{,},{-,}}; struct node
{
int x,y;
}; int go(int i,int j)
{
if(i>=&&i<=n&&j>=&&j<=m&&data[i][j]!='#')
return ;
return ;
} int bfs(int flag)
{
int cnt=;
node st,ed;
queue <node> q;
st.x=xi;
st.y=yi;
visit[xi][yi]=flag;
q.push(st);
while(!q.empty())
{
st=q.front();
q.pop();
visit[st.x][st.y]=flag;
if(data[st.x][st.y]=='C')
cnt++;
for(int i=;i<;i++)
{
ed.x=st.x+to[i][];
ed.y=st.y+to[i][];
if(go(ed.x,ed.y)&&visit[ed.x][ed.y]==)
{
visit[ed.x][ed.y]=flag;
q.push(ed);
}
}
}
map[flag]=cnt;
} int main()
{
scanf("%d",&t);
int res=;
while(t--)
{
res++;
scanf("%d%d%d",&n,&m,&q);
for(int i=;i<=n;i++)
for(int j=;j<=m;j++)
cin>>data[i][j];
memset(visit,,sizeof(visit));
memset(map,,sizeof(map));
printf("Case %d:\n",res);
for(int i=;i<=q;i++)
{
scanf("%d%d",&xi,&yi);
if(!visit[xi][yi])
bfs(i);
printf("%d\n",map[visit[xi][yi]]);
}
}
return ;
}
上一篇:java推送数据到app--极光推送


下一篇:asp.net WebService+Ajax调用