Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 7589 | Accepted: 3464 |
Description
Input
Output
Sample Input
3 6 HFDFFB AJHGDH DGAGEH
Sample Output
6
题意
必须满足 :
1. 不重复走过的路线
2. 不重复走过的字母
求最长路径
思路
1.深度优先算法
2.遍历所有可能性,取最大路径
方案
1. 不重复走过的路线
=》sign[r][c] = 1
2. 不重复走过的字母
=》twice[letter[r][c]-'A'] = 13.深度优先
=》递归实现
代码:
#include<stdio.h> int row,col,max; char letter[21][21]; int sign[21][21]; int twice[27]; int move[4][2] = {{-1,0},{1,0},{0,-1},{0,1}}; //up, down,left or right int judge(int r,int c) { if((r >= 0) && (r < row) && (c >= 0) && (c < col) && !twice[letter[r][c]-'A'] && !sign[r][c]) return true; else return false; } void visit(int r,int c,int step) { int rr,cc; twice[letter[r][c]-'A'] = 1; sign[r][c] = 1; if(max < step) max = step; for(int k = 0; k < 4; k++) { rr = r + move[k][0]; cc = c + move[k][1]; if(judge(rr,cc)) { visit(rr,cc,step+1); twice[letter[rr][cc]-'A'] = 0; sign[rr][cc] = 0; } } //return; } int main() { int i,j; max = 0; scanf("%d%d",&row,&col); for(i = 0; i < row; i++) scanf("%s",&letter[i]); for(i = 0; i < 21; i++) for(int j = 0; j < 21; j++) sign[i][j] = 0; for(i = 0; i < 27; i++) twice[i] = 0; visit(0,0,1); printf("%d",max); }