【算法练习】搜索dfs 百炼poj 1154:LETTERS

题目链接:http://bailian.openjudge.cn/practice/1154

 

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

题意:从(1,1)的位置开始从四个方向走,不能走相同字母的位置两次 ->提示要用 A-'A'做hash 标识visit数组

求最大的能走的格子的数目

 

思路:就用DFS进行dfs 然后回溯  再走不下去的时候判断有几个格子 再更新最后输出

//总感觉有点不对  但是顺利AC

#include<iostream>
#include <string.h>
using namespace std;

const int maxn=100;
int m,n,ct,res;
char G[maxn][maxn];
int visit[maxn];  //字母表示 'A'-'A'
int go[][2]={0,-1,
             0,1,
             1,0,
             -1,0};

bool inside(int x,int y){
    return x>=1 && x<=m && y>=1 && y<=n;
}

void DFS(int x,int y){
    //四个方向
    for(int i=0;i<4;i++){
        int xx=x+go[i][0];
        int yy=y+go[i][1];
        int ic=G[xx][yy]-'A';
        if(inside(xx,yy) && !visit[ic]){
            ct++;
            visit[ic]=1;
            DFS(xx,yy);
            visit[ic]=0;
            ct--;
        }
        else{
            if(res<ct)  res=ct;
        }
    }
}
int main(){
    memset(visit,0, sizeof(0));
    cin>>m>>n;
    for(int i=1;i<=m;i++){
        for(int j=1;j<=n;j++){
            cin>>G[i][j];
        }
    }
    ct=res=1;
    int c=G[1][1]-'A';
    visit[c]=1;
    DFS(1,1);
    cout<<res<<endl;
    return 0;
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值