LETTERS
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 7805 | Accepted: 3544 |
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
大致题意为:从(0,0)点开始搜,最多可以经过多少个不同的字母
H-A-D-G-J-F 为其中一种,经过了6个字母
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <queue>
#include <algorithm>
using namespace std;
int map[20][20];
int S,R;
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int vis[30];
int maxnum;
int countnum;
void dfs(int x,int y)
{
for(int i=0;i<4;i++)
{
int x1 = x+dir[i][0];
int y1 = y+dir[i][1];
if(x1<0||y1<0||x1>=S||y1>=R)
continue;
if(!vis[map[x1][y1]])
{
countnum++;
vis[map[x1][y1]]=1;
dfs(x1,y1);
maxnum=max(countnum,maxnum);
//状态还原
vis[map[x1][y1]]=0;
countnum--;
}
}
}
int main()
{
while(cin>>S>>R)
{
//初始值都要赋值为1
maxnum=1;
string str;
memset(vis,0,sizeof(vis));
for(int i =0;i<S;i++)
{
cin>>str;
for(int j=0;j<R;j++)
{
map[i][j] = str[j]-'A'+1;
//cout<<map[i][j]<<endl;
}
}
countnum=1;
vis[map[0][0]]=1;
dfs(0,0);
cout << maxnum << endl;
}
return 0;
}