1154:LETTERS

描述
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;

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值