void dfs_search(vector<string> &ans, string path, const string &num,
                    int target, int pos, long value, long pre_num){
        /*
        Put binary operator in pos, and then calculate the new value.

        @pre_num: when process *, we need to know the previous number.
        */
        if(pos == num.size()){
            if(value == target){
                ans.push_back(path);
            }
            return;
        }

        for(int i=1; i+pos<=num.size(); i++){
            string cur_str = num.substr(pos, i);
            // Digit can not begin with 0 (01, 00, 02 are not valid), except 0 itself.
            if(i>1 && cur_str[0] == '0')    break;
            long cur_d = stoll(cur_str);
            if(pos==0){
                dfs_search(ans, cur_str, num, target, pos+i, cur_d, cur_d);
            }
            // All three different binary operators: +, -, *
            else{
                dfs_search(ans, path+"+"+cur_str, num, target, pos+i, value+cur_d, cur_d);
                dfs_search(ans, path+"-"+cur_str, num, target, pos+i, value-cur_d, -cur_d);
                dfs_search(ans, path+"*"+cur_str, num, target, pos+i,
                           value-pre_num+pre_num*cur_d, cur_d*pre_num);
            }
        }
    }
Ejemplo n.º 2
0
    /*
    Classic backtracking problem.

    One key point: for one specified number,
    just scan itself and numbers larger than it to avoid duplicate combinations.
    Besides, the current path need to be reset after dfs call in general.
    Refer to:
    https://discuss.leetcode.com/topic/23142/python-dfs-solution
    */
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        if(candidates.size() == 0){
            return {};
        }
        sort(candidates.begin(), candidates.end());
        vector<vector<int>> ans;
        vector<int> path;
        dfs_search(candidates, 0, target, path, ans);
        return ans;
    }
Ejemplo n.º 3
0
 bool dfs_search(string word, int start, TrieNode *cur) {
     if (!cur) return false;
     if (start == word.size()) return cur->isKey;
     
     if (word[start] == '.') {
         for (int i = 0; i < 26; i++) {
             if (cur->ch[i]) {
                 if (dfs_search(word, start+1, cur->ch[i])) {
                     return true;
                 }
             }
         }
     }
     else {
         int index = word[start] - 'a';
         if (cur->ch[index]) {
             return dfs_search(word, start+1, cur->ch[index]);
         }
     }
     
     return false;
 }
Ejemplo n.º 4
0
 void dfs_search(vector<int>& candidates, int start, int target, vector<int> &path, vector<vector<int>> &ans){
     if(target==0){
         ans.push_back(path);
     }
     else{
         for(int i=start; i<candidates.size(); i++){
             if(candidates[i] > target){
                 return;
             }
             path.push_back(candidates[i]);
             dfs_search(candidates, i, target-candidates[i], path, ans);
             // Remember to do backtracking here.
             path.pop_back();
         }
     }
 }
Ejemplo n.º 5
0
void dfs_search(graph* g ,node* u)
{
	time += 1 ;
	u->d = time ;
	u->color = gray ;
	printf("%d " , u->idx) ;
	listnode* curnode ;
	for(curnode = g->adjlist[u->idx]->firstnode ; curnode != NULL ; curnode = curnode->next)
	{
		node* v = curnode->thisnode ;		
		if(v->color == white)
		{
			v->parent = u ;			
			dfs_search(g,v) ;
		}
	}
	time += 1 ;
	u->f = 	time ;
	u->color = black ;
}
int main() {
    int map[NODESIZE][NODESIZE]= {
        {0,1,0,0,0,1,1},
        {1,0,0,0,0,1,0},
        {0,0,0,1,1,0,0},
        {0,0,1,0,1,0,1},
        {0,0,1,1,0,1,0},
        {1,1,0,0,1,0,0},
        {1,0,0,1,0,0,0}
    };
    int answer[NODESIZE];
    answer[0]=STARTNODE;
    int visited[NODESIZE]= {};
    visited[STARTNODE]=1;
    printf("use backtrace:\n");
    backtrace(map,answer,1,visited);
    printf("use DFS:\n");
    dfs_search(map);
    printf("use BFS:\n");
    bfs_search(map);
}
Ejemplo n.º 7
0
void dfs(graph* g)
{
	int i ;
	time = 0 ;	

	printf("----- dfs starts ----\n") ;	
	for(i=1;i<= g->vertices ;i++)
	{
		g->v[i]->color = white ;
		g->v[i]->d = g->v[i]->f = 0 ;		
	}	

	for(i=1;i<= g->vertices ; i++)
	{
		if(g->v[i]->color == white)
		{
			g->v[i]->parent = NULL ;				
			dfs_search(g , g->v[i]) ;
			printf("\n") ;
		}
	}
	printf("------dfs ends----\n") ;	
}
Ejemplo n.º 8
0
 // Returns if the word is in the data structure. A word could
 // contain the dot character '.' to represent any one letter.
 bool search(string word) {
     if (word.empty()) {
         return false;
     }
     return dfs_search(word, 0, root);
 }
Ejemplo n.º 9
0
int IterativeDeepening::dfs_search(LiteState& current, int& bound, std::stack<LiteState>& path, Timer& timer) {
	
    if(!timer.is_still_valid()){
        return current.get_g();
    }
	
	// Perform heuristic evaluation
    double startTime = omp_get_wtime();
	int h = heuristic->calc_h(std::make_shared<LiteState>(current));
    heuristic_timer += (omp_get_wtime() - startTime);
    current.set_h(h);

	// Uses stack to trace path through state space
	path.push(current);

	// Bound check
	if (current.get_f() > bound){
        // Remove this state from the back of the vector
		path.pop();
		//path.erase(path.begin() + path.size() - 1);
		nodes_rejected++;
		int f = current.get_f();
		state_space.remove(std::shared_ptr<LiteState>(new LiteState(current)));
		return f;
	}

	if (state_space.state_is_goal(current, goals)){

		timer.stop_timing_search();
		print_steps(path);
		solved = true;

        std::cout << "Nodes generated during search: " << nodes_generated << std::endl;
        std::cout << "Nodes expanded during search: " << nodes_expanded << std::endl;

        std::cout << "Sequential search took " << timer.get_search_time() << " seconds." << std::endl;
        std::cout << "Time spent calculating heuristic: " << heuristic_timer << " seconds." << std::endl;
		
		return current.get_f();
	}

	nodes_expanded++;
	int min = Search::protect_goals;

	const std::vector<Operator>& applicable_operators = get_applicable_ops(current);

	for (std::size_t i = 0; i < applicable_operators.size(); i++) {

		const Operator& op = applicable_operators[i];

		// Generate successor state, set path cost
		LiteState child = get_successor(op, current);
		int new_g = current.get_g() + op.get_cost();
		child.set_g(new_g);

		// Check if state has been visited, if it has check if we have reached it in fewer steps (lower g value)
		if (state_space.child_is_duplicate(std::shared_ptr<LiteState>(new LiteState(child)))) {
			nodes_rejected++;
			continue;
		}

		// Record operator
		int op_id = op.get_num();
		child.set_op_id(op_id);

		nodes_generated++;

        int t = 0;
 		// Explore child node
		t = dfs_search(child, bound, path, timer);
		if (t < min){
			min = t;
		}
		// Get out of recursion when done. 
		if (solved){
			break;
		}
	}
	// We have generated no children that have lead to a solution and are backtracking.
	// Erase node as we backtrack through state space
	path.pop();
	return min;
}
Ejemplo n.º 10
0
bool IterativeDeepening::find_plan() {

	int init_h = heuristic->calc_h(std::make_shared<LiteState>(initial_state));

	int bound = 0;
	int result = 0;

	// Test beginning heuristic to ensure it is a solvable task.
	if (init_h == std::numeric_limits<int>::max()) {
		std::cout << "Initial estimate assumes unsolvable." << std::endl;
		return false;
	}

	initial_state.set_g(bound);
	initial_state.set_h(init_h);
	bound = init_h;

	std::cout << "Initial heuristic estimate: " << init_h << std::endl;
    timer.start_timing_search();

	while (timer.is_still_valid()) {

		state_space = StateSpace();

		std::shared_ptr<LiteState> root(new LiteState(initial_state));

		state_space.add_initial_state(root);
		nodes_expanded = 0;
		nodes_generated = 0;
		nodes_rejected = 0;
		//std::vector<LiteState> path;
		std::stack<LiteState> path;

		result = dfs_search(initial_state, bound, path, timer);

		if (solved) {
            break;
		}
		else {

            std::cout << "Nodes generated during iteration: " << nodes_generated << std::endl;
            std::cout << "Nodes expanded during iteration: " << nodes_expanded << std::endl;
            std::cout << "Nodes rejected during iteration: " << nodes_rejected << std::endl;

            if (result >= 100000 && Search::protect_goals) {
                std::cout << "Disabling goal protection." << std::endl;
                Search::protect_goals = false;
            } else {
                bound = result;
			}
		}

		state_space.clear();

		std::cout << "Depth reached, adjusting bound to " << bound << std::endl;
	}
    if (!solved) {
		std::cout << "Time limit exceeded." << std::endl;
	}

	return solved;
}
    /*
    Once you can understand the solution space tree, you just get it.

    Refer to:
    https://discuss.leetcode.com/topic/24523/java-standard-backtrace-ac-solutoin-short-and-clear
    */
    vector<string> addOperators(string num, int target) {
        vector<string> ans;
        dfs_search(ans, "", num, target, 0, 0, 0);
        return ans;
    }