LeetCode Word Ladder

 //小的能过,大的内存超限,故大于3000则不处理  :)
1
char edge[3000][3000]={0}; 2 int len[3000]={0}; 3 4 class Solution { 5 public: 6 7 int countL; 8 int findShort() 9 { 10 int i,j,k; 11 len[0]=0; 12 vector<int> q,qq; 13 q.push_back(0); 14 for( ;q.size(); ) 15 { 16 for(j=0;j<q.size();j++) 17 { 18 int ttt=q[j]; 19 for(k=0;k<countL;k++) 20 { 21 if(edge[ttt][k]) 22 { 23 if(len[ttt]!=-1&&len[k]==-1) 24 { 25 len[k]=len[ttt]+1; 26 qq.push_back(k); 27 } 28 } 29 } 30 } 31 q=qq; 32 qq.clear(); 33 } 34 return len[1]; 35 } 36 void initLen() 37 { 38 int i; 39 for(i=0;i<countL;i++) 40 len[i]=-1; 41 } 42 bool cal(string &s1,string &s2) 43 { 44 const char*p=s1.c_str(); 45 const char*q=s2.c_str(); 46 int i=0; 47 int c=0; 48 for(;p[i];i++) 49 { 50 if(p[i]!=q[i]) 51 c++; 52 } 53 if(c==1) 54 return true; 55 return false; 56 } 57 void calMatrix(vector<string> &v) 58 { 59 int i,j; 60 for(i=0;i<v.size();i++) 61 { 62 for(j=0;j<v.size();j++) 63 { 64 if(cal(v[i],v[j])) 65 edge[i][j]=1; 66 } 67 } 68 } 69 int ladderLength(string start, string end, unordered_set<string> &dict) { 70 // Start typing your C/C++ solution below 71 // DO NOT write int main() function 72 memset(edge,0,9000000); 73 vector<string> v; 74 unordered_set<string> ::iterator p; 75 v.push_back(start); 76 v.push_back(end); 77 for(p=dict.begin();p!=dict.end();p++) 78 { 79 v.push_back(*p); 80 } 81 82 countL=v.size(); 83 if(countL>2000) 84 return 1000; 85 calMatrix(v); 86 initLen(); 87 int len2=findShort(); 88 if(len2!=-1) 89 return len2+1; 90 return 0; 91 } 92 };
原文地址:https://www.cnblogs.com/mengqingzhong/p/3115187.html