LETTERS
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 5601 | Accepted: 2661 |
Description
A single-player game is played on a rectangular board divided in R rows and C columns. There is a single uppercase letter (A-Z) written in every position in the board.
Before the begging of the game there is a figure in the upper-left corner of the board (first row, first column). In every move, a player can move the figure to the one of the adjacent positions (up, down,left or right). Only constraint is that a figure cannot visit a position marked with the same letter twice.
The goal of the game is to play as many moves as possible.
Write a program that will calculate the maximal number of positions in the board the figure can visit in a single game.
Before the begging of the game there is a figure in the upper-left corner of the board (first row, first column). In every move, a player can move the figure to the one of the adjacent positions (up, down,left or right). Only constraint is that a figure cannot visit a position marked with the same letter twice.
The goal of the game is to play as many moves as possible.
Write a program that will calculate the maximal number of positions in the board the figure can visit in a single game.
Input
The first line of the input contains two integers R and C, separated by a single blank character, 1 <= R, S <= 20.
The following R lines contain S characters each. Each line represents one row in the board.
The following R lines contain S characters each. Each line represents one row in the board.
Output
The first and only line of the output should contain the maximal number of position in the board the figure can visit.
Sample Input
3 6 HFDFFB AJHGDH DGAGEH
Sample Output
6
Source
毫无技术含量的dfs 但是还是wa了好长时间,最后将计数从一开始记录 飘过~~~~
code:
#include<iostream>
#include<string.h>
using namespace std;
char map[50][50];;
int vis[50][50];
int mark[50];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
int sum;
int n,m;
void dfs(int sx,int sy,int ans)
{
for (int i=0;i<4;i++)
{
int nowx=sx+dir[i][0],nowy=sy+dir[i][1];
if (nowx<n&&nowy<m&&nowx>=0&&nowy>=0&&!vis[nowx][nowy]&&!mark[map[nowx][nowy]-'A'])
{
mark[map[nowx][nowy]-'A']=1;
vis[nowx][nowy]=1;
ans++;
if (ans>sum)
sum=ans;
dfs(nowx,nowy,ans);
mark[map[nowx][nowy]-'A']=0;
vis[nowx][nowy]=0;
ans--;
}
}
}
int main()
{
cin>>n>>m;
memset(map,0,sizeof(map));
memset(vis,0,sizeof(vis));
memset(mark,0,sizeof(mark));
sum=1;//这里从1开始记录 因本身就是1个~
for (int i=0;i<n;i++)
for (int j=0;j<m;j++)
{
cin>>map[i][j];
}
vis[0][0]=1;
mark[map[0][0]-'A']=1;
dfs(0,0,1);
cout<<sum<<endl;
return 0;
}