1154:LETTERS(搜索练习1)

闲聊一下:

        今早和葛葛一块做实验,确实是发现了自己有很大的不足,特别在算法这块感觉自己就是想要AC就行了,但是葛葛却一直在寻找最优方案,还有一些条件限制,觉得自己跟人家水平确实还是有很多差距的,还是需要认真思考每一个算法,争取尽快赶上他。

        以后本菜菜每天都会更新关于搜索的题目的,跟着费费的学习每一天都很开心,就是有点难,其实上课听得确实很明白,然后自己做的时候嘛,就不太好,搜索是万能之法,所以一定要熟练掌握才行。
题目描述:
        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.简单的dfs搜索的题目。

2.确定四个搜索的方向。

3.因为是字符串嘛,所以搜索vis数组,要将字符串-‘A’,用数字来判断该字符是否已经已经被搜索过了(个人觉得就是映射的一个原理吧,之前哈希表也用过,当时还复习了好长时间呢)。

4.进行下一次搜索次数加一,计数器更新,注意dfs里的回溯即可。

代码如下:

#include <iostream>
#include <cstring>
using namespace std;
//上下左右
int dx[] = { -1,1,0,0 };
int dy[] = { 0,0,-1,1 };
int ans = 0;
int vis[30];
char mp[30][30];//别定义错类型啊
int n, m;
void dfs(int index,int x,int y) {
    if (index > ans) {
        ans = index;
    }
    for (int i = 0; i < 4; i++) {
        int xx = x + dx[i];
        int yy = y + dy[i];       
        if ((xx > 0 && xx <= n && yy > 0 && yy <= m) && !vis[mp[xx][yy]-'A']) {
            vis[mp[xx][yy]-'A'] = 1;
            dfs(index + 1, xx, yy);
            vis[mp[xx][yy]-'A'] = 0;
        }
    }
}
int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cin >> mp[i][j];
        }
    }
    memset(vis, 0, sizeof(vis));
    vis[mp[1][1] - 'A'] = 1;
    dfs(1, 1, 1);//现在主要的问题就是如何写dfs
    cout << ans << endl;

}

 撒花!

        我的效率果然是出奇的低,但好不容易算是干完了,今天周末,干完饭再干一题,然后开始我最爱的大根堆,小跟堆的基础梳理了,持续更新中....

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

钟一淼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值