openjudge156_LETTERS

openjudge156_LETTERS

时空限制    1000ms/64MB

描述

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.

输入

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 first and only line of the output should contain the maximal number of position in the board the figure can visit.

样例输入

3 6
HFDFFB
AJHGDH
DGAGEH

样例输出

6

代码

#include<iostream>
using namespace std;
const int N = 25;
const int dx[] = { 0, 1, 0,-1},
		  dy[] = { 1, 0,-1, 0};
int r,s,num[128],ans;
char a[N][N];
bool visited[N][N];

void search(int x,int y,int step){
	if (ans<step) ans=step;
	for (int i=0; i<4; i++){
		int xx=x+dx[i],yy=y+dy[i];
		if (xx>=1 && xx<=r && yy>=1 && yy<=s && !visited[xx][yy] && !num[a[xx][yy]]){
			num[a[xx][yy]] = true;	//新字母记录
			visited[xx][yy] = true;	//新字母标记
			search(xx,yy,step+1);
			num[a[xx][yy]] = false;
			visited[xx][yy] = false;
		}
	}
}

int main(){
	cin>>r>>s;
	for (int i=1; i<=r; i++)
		for (int j=1; j<=s; j++) cin>>a[i][j];
	num[a[1][1]] = true;	//第一个字母记录
	visited[1][1] = true;	//第一个字母标记
	search(1,1,1);	//坐标(1,1)开始搜索,已走过1个字母
	cout<<ans<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/WDAJSNHC/article/details/81346597
156
今日推荐