POJ 156:LETTERS(dfs)

题目:忘题戳这

题目大意:一个表格中每处有字母,从左上角开始走,不能经过重复的字母,看你最多能走多少个格子(包括左上角的起点格子)

分析:一道非常典型的搜索题,寻路问题。

深搜的同时,根据条件进入深搜(即没走过则进入,走过则跳过)

用到的变量大概有,maxpos 记录历史能走的最多的步数,nowpos记录当前走了多少格,

visit[i] 记录i点有没有走过,map[i][j]地图,还有行和列r c。

小技巧:用字母减"A",即可得到某字母唯一对应的数字,应用于visit下标。

AC代码:

#include
using namespace std;
int row, col;
char map[25][25];
int maxpos = -1;
int visit[100];
int nowpos;
int dx[] = { 0,1,-1,0 };
int dy[] = { 1,0,0,-1 };//方向数组,东南西北
void dfs(int r, int c, int nowpos);
int main() {
	cin >> row >> col;
	for (int i = 0; i < row; i++) {
		for (int j = 0; j < col; j++) {
			cin >> map[i][j];
		}
	}
	dfs(0, 0, 0);//从左上角进入,走过的格数为零开始
	cout << maxpos << endl;
	return 0;
}
void dfs(int r, int c, int nowpos) {
	if (visit[map[r][c] - 'A'] == 0 && r >= 0 && r < row && c >= 0 && c < col) {
		//进入条件是:没走过,没越界
		visit[map[r][c] - 'A'] = 1;//标记走过
		nowpos++;//现在走过的位置加一
		maxpos = nowpos > maxpos ? nowpos : maxpos;//更新答案
		for (int i = 0; i < 4; i++) {
			int nr = r + dx[i];
			int nc = c + dy[i];//向各个方向深搜
			dfs(nr, nc, nowpos);
		}
		visit[map[r][c] - 'A'] = 0;
		//回溯:即走过了从 r c 开始引流的所有路,走到这就说明
		//从r c开始后的路都走了,现在就不走r c了。
	}
	else return;
}

感谢阅读!!!

你可能感兴趣的:(#,POJ,深度优先,算法)