您的位置:首页 > 其它

1154:LETTERS

2016-06-04 21:46 405 查看
描述

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

典型的深度优先搜索

用result 来记录路径最长的长度,用passBy[]来记录走过的字母(tips:字母有唯一的ASC码减去’A’就可以当作是index)

当然不要忘了还要进行边界的判断。

这是深度优先搜索的基本格式:

passBy[index]=true;
search(row, column,dep+1);
passBy[index]=false;


#include <iostream>
#include <set>
#include <stdio.h>
#include <algorithm>
#include <cstring>
using namespace std;

int rowBoundary;
int columnBoundary;
char game[20][20];
bool passBy[30];
int result=0;

// #define max(a, b)  (((a) > (b)) ? (a) : (b))

void search(int row,int column,int dep){

if(result<dep)
result=dep;
if(!passBy[game[row][column]-'A']){
passBy[game[row][column]-'A']=true;
if(row+1<rowBoundary)
search(row+1, column,dep+1);
if(row-1>=0)
search(row-1, column,dep+1);
if(column+1<columnBoundary)
search(row, column+1,dep+1);
if(column-1>=0)
search(row, column-1,dep+1);
passBy[game[row][column]-'A']=false;
}

}
int main(int argc,char const * argv[]){
cin>>rowBoundary;
cin>>columnBoundary;

for(int i=0;i<rowBoundary;i++){
for(int j=0;j<columnBoundary;j++){
cin>>game[i][j];
}
getchar();
}

memset(passBy,false,sizeof(passBy));
//passBy[game[0][0]-'A']=true;
search( 0,0,0);
cout <<result<<endl;

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  深度优先搜索