poj 1154 LETTERS

本文介绍了一个基于深搜的游戏路径探索算法。游戏在一个由字母组成的矩形棋盘上进行,目标是尽可能多地移动游戏棋子,但不能两次进入同一个字母的位置。文章提供了完整的C++代码实现,并解释了如何通过深度优先搜索寻找最长路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LETTERS
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 6009 Accepted: 2847

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


分析:简单的深搜从(0,0)开始进行搜索,然后找到最长的路。需要将每一个字母进行标记。


#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char map[101][101];
bool vis[101];
int dir[4][2]={1,0,0,1,-1,0,0,-1};
int ans,n,m;
int check(int x,int y)
{
    if(x>=0&&x<n&&y>=0&&y<m&&!vis[map[x][y]-'A'])
    return 1;
    return 0;
}
void dfs(int dep,int x,int y)
{
    if(dep>ans)
    {
        ans=dep;
    }
    for(int i=0;i<4;i++)
    {
        int tx=x+dir[i][0];
        int ty=y+dir[i][1];
        if(check(tx,ty))
        {
            vis[map[tx][ty]-'A']=true;
            dfs(dep+1,tx,ty);
            vis[map[tx][ty]-'A']=false;
        }
    }
}
int main()
{
    while(scanf("%d %d",&n,&m)==2)
    {
        ans=0;
        memset(vis,false,sizeof(vis));
        for(int i=0;i<n;i++)
        {
           for(int j=0;j<m;j++)
           {
               cin>>map[i][j];
               map[i][j]-='A';
           }
        }
        vis[map[0][0]-'A']=true;
        dfs(1,0,0);
        cout<<ans<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值