题意:输入行数和列数,然后输入大写字母的矩阵,从左上角出发,只能上下左右走,求能够经过的不重复字母的最多的个数。
题解
1 /* 2 基础的dfs 3 */ 4 #include <iostream> 5 #include <vector> 6 7 using namespace std; 8 9 int ans, n, m; 10 string map[21]; 11 int direction[4][2] = { 0, -1, -1, 0, 0, 1, 1, 0 }; 12 int visited[30]; 13 14 void dfs(int i, int j, int num) 15 { 16 ans = max(ans, num); 17 for (int k = 0; k < 4; ++k) { 18 int ii = i + direction[k][0]; 19 int jj = j + direction[k][1]; 20 if ((ii < 0) || (jj < 0) || (ii >= n) || (jj >= m)) continue; 21 if (visited[map[ii][jj] - 'A']) continue; 22 visited[map[ii][jj] - 'A'] = 1; 23 dfs(ii, jj, num + 1); 24 visited[map[ii][jj] - 'A'] = 0; 25 } 26 } 27 28 int main() 29 { 30 for (int i = 0; i < 30; ++i) visited[i] = 0; 31 cin >> n >> m; 32 for (int i = 0; i < n; ++i) cin >> map[i]; 33 ans = 1; 34 visited[map[0][0] - 'A'] = 1; 35 dfs(0, 0, 1); 36 cout << ans << endl; 37 return 0; 38 }