[POJ_1054]LETTERS

Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 7589   Accepted: 3464

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.

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.

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

题意 

必须满足 :

1. 不重复走过的路线

2. 不重复走过的字母

求最长路径

思路

1.深度优先算法

2.遍历所有可能性,取最大路径

方案

1. 不重复走过的路线

=》sign[r][c] = 1        

2. 不重复走过的字母

=》twice[letter[r][c]-'A'] = 1

3.深度优先

=》递归实现


代码:

#include<stdio.h>

int row,col,max;
char letter[21][21];
int sign[21][21];
int twice[27];
int move[4][2] = {{-1,0},{1,0},{0,-1},{0,1}}; //up, down,left or right

int judge(int r,int c)
{
	if((r >= 0) && (r < row) && (c >= 0) && (c < col) && !twice[letter[r][c]-'A'] && !sign[r][c])
		return true;
	else
		return false;
}

void visit(int r,int c,int step)
{
	int rr,cc;

	twice[letter[r][c]-'A'] = 1;
	sign[r][c] = 1;

	if(max < step) max = step;
	for(int k = 0; k < 4; k++)
	{
			
		rr = r + move[k][0];
		cc = c + move[k][1];

		if(judge(rr,cc))
		{
			visit(rr,cc,step+1);
			twice[letter[rr][cc]-'A'] = 0;
			sign[rr][cc] = 0;
		}

	}
	
	//return;
}

int main()
{
	int i,j;
	max = 0;

	scanf("%d%d",&row,&col);
	for(i = 0; i < row; i++)
		scanf("%s",&letter[i]);

	for(i = 0; i < 21; i++)
		for(int j = 0; j < 21; j++)
			sign[i][j] = 0;

	for(i = 0; i < 27; i++)
		twice[i] = 0;

	visit(0,0,1);

	printf("%d",max);

}



你可能感兴趣的:(poj,深度优先)