Example #1
0
 vector<vector<string> > findLadders(string start, string end, unordered_set<string> &dict) {
     allstr.clear();
     res.clear();
     
     if (dict.size() == 0) return res;
     if (start == end) {
         vector<string> justone(1, start);
         res.push_back(justone);
         return  res;
     }
     
     allstr.push_back(make_pair(start, 1));
     allstr.push_back(make_pair(end, 0));
     
     for (unordered_set<string>::iterator pos = dict.begin(); pos != dict.end(); ++ pos) {
         if (*pos != start && *pos != end) {
             allstr.push_back(make_pair(*pos, 0));
         }
     }
     
     _makeLinks();
     
     int step = _ladderLen();
     
     stk.clear();
     stk.push_back(1);
     _DFS(step);
     return res;
 }
Example #2
0
void _DFS(mgraph *mg, int v) {
	int u;
	static int visited[MAXN] = {0};

	printf("%s ", mg->vertex[v]);
	visited[v] = 1;

	u = firstadj(mg, v);
	while (u != -1) {
		if (!visited[u]) {
			_DFS(mg, u);
		}
		u = nextadj(mg, v, u);
	}
}
Example #3
0
int main(int argc, const char *argv[])
{
	char * 	v[N] = {"V0", "V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8"};
    int edge[N][N]={   //v0 v1 v2 v3 v4 v5 v6 v7 v8
                 /*v0*/ {0, 1, 1, 0, 0, 0, 0, 0, 0},
                 /*v1*/ {1, 0, 0, 1, 0, 1, 0, 0, 0},
                 /*v2*/ {1, 0, 0, 0, 0, 0, 1, 1, 0},
                 /*v3*/ {0, 1, 0, 0, 1, 0, 0, 0, 0},
                 /*v4*/ {0, 0, 0, 1, 0, 1, 0, 0, 1},
                 /*v5*/ {0, 1, 0, 0, 1, 0, 0, 0, 0},
                 /*v6*/ {0, 0, 1, 0, 0, 0, 0, 1, 0},
                 /*v7*/ {0, 0, 1, 0, 0, 0, 1, 0, 0},
                 /*v8*/ {0, 0, 0, 0, 1, 0, 0, 0, 0}
    };
	mgraph * mg;

	mg = mgraph_create(N, v, edge);

	//int visited[N] = {0};
	//DFS(mg, 0, visited);
	_DFS(mg, 0);
	puts("");

	_BFS(mg, 0);

	if (topsort(mg)) {
		printf("not cycle\n");
	}
	else {
		printf("cycle\n");
	}

	//int (*p)[N];
//	p = edge;
#if 0
	
	int u = firstadj(mg, 7);//u=1
	printf("%d %s \n", u, v[u]);//1 V1

	u = nextadj(mg, 7, u);//u=2
	printf("%d %s \n", u, v[u]);//1 V1

#endif

	return 0;
}
Example #4
0
 void _DFS(int step) {
     int now = stk[stk.size() - 1];
     if (allstr[now].second != step + 1 - stk.size()) return ;
     if (stk.size() == step) {
         if (now == 0) {
             vector<string> oneres;
             for (int i = stk.size() - 1; i >= 0; --i) {
                 oneres.push_back(allstr[stk[i]].first);
             }
             res.push_back(oneres);
         }
         return ;
     }
     for (int i = 0; i < links[now].size(); ++i) {
         stk.push_back(links[now][i]);
         _DFS(step);
         stk.pop_back();
     }
 }
Example #5
0
 vector<vector<string> > solveNQueens(int n) {
     ans.clear();
     now.clear();
     _DFS(0, n, 0, 0, 0);
     return ans;
 }