闲聊一下:
今早和葛葛一块做实验,确实是发现了自己有很大的不足,特别在算法这块感觉自己就是想要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;
}
撒花!
我的效率果然是出奇的低,但好不容易算是干完了,今天周末,干完饭再干一题,然后开始我最爱的大根堆,小跟堆的基础梳理了,持续更新中....