其他分享
首页 > 其他分享> > 156:LETTERS

156:LETTERS

作者:互联网

描述
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

解题

用dfs搜索算法,
有两组判断条件,一个和往常一样是某个位置是否被访问过,另一个是这个字符是否被访问过
因为字母规整且数目确定,可以直接把字符转成数字存在数组中

代码

#include <cstring>
#include <iostream>
using namespace std;
bool letters[30], vis[25][25];  //字符是否访问,位置是否访问
int m, n, all[25][25], ans = 0; // m,n,地图,答案
int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; //方向
void dfs(int x, int y, int dep) {
    if (dep > ans) ans = dep;
    for (int i = 0; i < 4; i++) { //四个方向递归
        int xx = x + dir[i][0], yy = y + dir[i][1];
        if (xx >= 0 && xx < m && yy >= 0 && yy < n && !vis[xx][yy] &&
            !letters[all[xx][yy]]) {
            vis[xx][yy] = true;
            letters[all[xx][yy]] = true;
            dfs(xx, yy, dep + 1);
            vis[xx][yy] = false;
            letters[all[xx][yy]] = false;
        }
    }
}
int main() {
    cin >> m >> n;
    char temp;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            cin >> temp;
            all[i][j] = temp - 'A'; //转整数
        }
    }
    vis[0][0] = true;
    letters[all[0][0]] = true;
    dfs(0, 0, 1);
    cout << ans;
}

标签:LETTERS,156,int,yy,xx,board,&&,letters
来源: https://blog.csdn.net/xcdq_aaa/article/details/116399703