Welcome to our website.

Finding the Longest Path of Distinct Letters with DFS

Idea

  • Use DFS.
  • From the problem constraints, starting from the letter in the upper-left corner, there can be at most 26 different letters on the path.
  • So we can use a vis array to record whether a letter has already been used on the current path. If it has been visited, mark it as True.
  • Recursively process each cell. At every level, use direction offsets to explore the four neighboring cells: up, down, left, and right.
  • Maintain res to store the maximum number of distinct letters that can be collected. Update it whenever a longer path is found. Once res == 26, the best possible answer has been reached, so we can return early.
  • Note that the starting letter must also be marked as visited before the search begins.

Code

#include <bits/stdc++.h>
using namespace std;

const int N = 100;

int n, m, res;

char mp[N][N];

bool vis[N * 3];  // 记录字母 ASCII 码的状态以标记其是否走过

int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};

void dfs(int x, int y, int cnt){
    res = max(res, cnt);  // 更新最大值
    if(res == 26) return;  // 达到最大值提前返回
    for(int i = 0; i < 4; i ++){
        int l = x + dx[i], r = y + dy[i];
        if(l >= 0 && l < n && r >= 0 && r < m && !vis[mp[l][r]]){  // 满足在边界内,且没有走过
            vis[mp[l][r]] = 1;  // 标记为走过
            dfs(l, r, cnt + 1);  // 递归走下一层
            vis[mp[l][r]] = 0;  // 恢复现场
        }
    }
}

void solve(){
    cin >> n >> m;
    for(int i = 0; i < n; i ++) cin >> mp[i];  // 读入地图,下标从 (0, 0) 开始
    vis[mp[0][0]] = 1;  // 标记起始点已经走过
    dfs(0, 0, 1);  // 从 (0, 0) 开始搜索
    cout << res << endl;
}

int main(){
    solve();
    return 0;
}

Related Posts