百练1154:LETTERS

1154:LETTERS

  • 查看
  • 提交
  • 统计
  • 提示
  • 提问
总时间限制: 
1000ms 
内存限制: 
65536kB
描述
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
来源
Croatia OI 2002 Regional Competition - Juniors
*************************************************
其实这道题我看出来了是深搜.....也知道用递归.....甚至大致的套路心里也有数,但是没敢写,因为我不清楚递归推出的条件是什么,也就是不知道if什么才能return这句话不知道该怎么写。。但是找了网上代码之后,才看出来。。递归并不一定需要显式的退出条件:
(代码来自:http://blog.csdn.net/qq_27601815/article/details/73741564)
#include  
#include  
#include  
using namespace std;  
  
char mapp[22][22];  
int n,m;  
  
int book[122];  //这个数组很巧妙,我猜作者是考虑到字母的ascii码最大是97+25=122.
                //所以直接用字母做索引,因为他本身也是数字。但实际上大写字母的话到65+25=90应该就可以了。

int dire[4][2]={-1,0,1,0,0,-1,0,1};  //这个是4个方向的坐标变化数,一般这种棋盘、矩阵、迷宫类的题目经常用到。
int ans;  
  
void dfs(int x,int y,int step)		//传入的参数为,当前的坐标和当前已经走的步数  
{  
    ans=max(ans,step);  		//上一次的步数和当前的步数相比,取较大的
      
    for(int i=0;i<4;i++)  		
    {  
            int nx=dire[i][0]+x;  
            int ny=dire[i][1]+y;  	//nx,ny记录变化后的坐标
            if(nx<=0||nx>n||ny<=0||ny>m)continue;  //如果越界,则进行下一次循环。这个实际上就是退出循环的条件,因为没进到下面if里
						  //也就没进入下一次递归
            if(!book[mapp[nx][ny]]){  
                book[mapp[nx][ny]]++;  
                dfs(nx,ny,step+1);   
                book[mapp[nx][ny]]--;  		//典型的回溯过程。个人觉得book数组改成bool型的标志数组也可以
            }   
    }  					//for循环,遍历4种可能的运动方式
}  
int main()  
{  
    cin>>n>>m;  
    getchar();  
    for(int i=1;i<=n;i++)  
    {  
        for(int j=1;j<=m;j++)  
        {  
            cin>>mapp[i][j];  
        }  
        getchar();  
    }  				//注意字符的输入方式,用getchar吸收空格
    book[mapp[1][1]]++;  
    dfs(1,1,1);  
      
    cout<

*****************************

坚持,而不是打鸡血~

你可能感兴趣的:(搜索,递归,DFS)