Esempio n. 1
0
 int backtracking(int r, int c, int m, int n, vector<vector<int> > &mem) {
     if(r==m && c==n) return 1;
     if(r>m || c>n) return 0;
     if(mem[r+1][c]==-1) mem[r+1][c]=backtracking(r+1, c, m, n, mem);
     if(mem[r][c+1]==-1) mem[r][c+1]=backtracking(r, c+1, m, n, mem);
     return mem[r+1][c] + mem[r][c+1];
 }
 // left, right分别代表剩余'('和')'的个数
 void backtracking(vector<string> &res, string str, int left, int right) {
     if(left == 0 && right == 0) {
         res.push_back(str);
         return ;
     }    
     if(left > 0) 
         backtracking(res, str+'(', left-1, right);
     if(right > left) 
         backtracking(res, str+')', left, right-1);
 }
Esempio n. 3
0
void backtracking(int nivel, int numElementosNivel, bool output) {
	if (numElementosNivel == TAM_SUBCONJUNTO && output) {
		imprime();
		return;
	} else if (nivel == k)
		return;
	solucao[numElementosNivel] = conjunto[nivel];
	backtracking(nivel + 1, numElementosNivel + 1, true);
	backtracking(nivel + 1, numElementosNivel, false);
}
Esempio n. 4
0
int main() {
  if (n % 2 == 0) {
    backtracking(setbits(n/2), 0, 0, 0, 0);
    std::cout << 2*count << " " << nodes << "\n";
  }
  else {
    backtracking(setbits(n/2), 0, 0, 0, 0);
    const count_t half = count; count = 0;
    backtracking(queen_t().set(n/2), 0, 0, 0, 0);
    std::cout << 2*half + count << " " << nodes << "\n";
  }
}
 vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
     sort(candidates.begin(), candidates.end());
     vector<vector<int>> res;
     vector<int> tmp;
     backtracking(res, candidates, tmp, target, 0);
     return res;
 }
vector<string> Solution::generateParenthesis(int A) {
    vector<string> res;
    
    if (A>0)
        backtracking(A, 0, 0, "", res);
    return res;
}
Esempio n. 7
0
int main(int argc, const char * argv[])
{
    short n, i, j, l;
    
    for(i = 0; i < 35; i++)
    {
        havePrinter[i] = 0;
        for(j = 0; j < 35; j++)
        {
            graph[i][j] = 0;
        }
    }
    
    scanf("%hd", &n);
    while(scanf("%hd %hd", &j, &l) != EOF)
    {
        graph[j-1][l-1] = 1;
        graph[l-1][j-1] = 1;
    }
        
    best = n;
    actualPrinters = 0;
    backtracking(n, -1, actualPrinters);

    printf("%hd\n", best);
    return 0;
}
Esempio n. 8
0
int		main(int ac, char **av)
{
	int			fd;
	t_list		**lst;

	if (ac == 2)
	{
		if (!(lst = (t_list**)malloc(sizeof(t_list*))))
			return (-1);
		*lst = NULL;
		if (((fd = open(av[1], O_RDONLY)) == -1))
		{
			ft_putendl("error");
			return (-1);
		}
		if (!(check_file(lst, fd)))
		{
			error(lst);
			return (close(fd) == -1 ? -1 : 0);
		}
		backtracking(lst, square_size(ft_alphabet('a') - 64));
		if (close(fd) == -1)
			return (-1);
	}
	else
		ft_putendl("error");
	return (0);
}
Esempio n. 9
0
void Sudoku::Solve()
{
	if (status == UNSOLVABLE)
		printf("0\n");
	else
	{
		backtracking(0);

		if (status == MULTI_SOLUTION)
			printf("2\n");
		else if (status == ONE_SOULUTION)
		{
			printf("1\n");
			for (int i = 0; i < 9; i++)
			{
				for (int k = 0; k < 9; k++)
				{
					if (!k) printf("%d", answer[i*9+k]);
					else printf(" %d", answer[i*9+k]);
				}
				putchar('\n');
			}
		}
		else
		{
			status = UNSOLVABLE;
			printf("0\n");
		}
	}
}
Esempio n. 10
0
void backtracking(node_t *currentNode, connection_t *currentSolution, connection_t *globalSolution)
{
	//Move to the neighbors
	int i;
	for(i = 0; i < currentNode->n_neighbors; i++) {
		//Check if solution
		if(currentNode->neighbors[i] == currentSolution->destination &&
				currentNode->n_connections[i]) {
			backtracking_compareSolutions(globalSolution, currentSolution);
			continue;
		}

		//If no more connections, skip to next neighbor
		if(!node_use_connection(currentNode, currentNode->neighbors[i]->name))
			continue;

		//Move forward
		connection_push(currentSolution, currentNode->neighbors[i]);
		backtracking(currentNode->neighbors[i], currentSolution, globalSolution);

		//Move backwards
		connection_pop(currentSolution);
		node_free_connection(currentNode, currentNode->neighbors[i]->name);
	}
}
Esempio n. 11
0
 vector<vector<int>> subsets(vector<int>& nums) {
     sort(nums.begin(),nums.end());
     vector<vector<int>> ans;
     vector<int> result;
     backtracking(ans,result,nums,0);
     return ans;
     
 }
Esempio n. 12
0
 vector<vector<int> > subsetsWithDup(vector<int>& nums) {
     sort(nums.begin(),nums.end());
     vector<int> solu;
     for (int i=0;i<=nums.size();i++){
         backtracking(nums,0,i,solu);
     };
     return ret;
 };
Esempio n. 13
0
// u = vertice de partida, k = nivel na arvore (qtidade de elementos na particao)
void backtracking(int u, int k) { // obtem a melhor quantidade partindo de u
        naParticao[k++] = u;
        if (k > melhor)
                melhor = k;
        for (int candidato = u + 1; candidato < N; candidato++)
                if (podeDescer(candidato, k))
                        backtracking(candidato, k);
}
Esempio n. 14
0
 int uniquePaths(int m, int n) {
     int **mem = new int*[m+1];
     for(int i=0; i<=m; ++i) {
         mem[i] = new int[n+1];
         for(int j=0; j<=n; ++j)
             mem[i][j] = -1;
     }
     return backtracking(0, 0, m-1, n-1, mem);
 }
Esempio n. 15
0
 void backtracking(vector<vector<int>> &ans,vector<int> result,vector<int>nums,int idx)
 {
     ans.push_back(result);
     for(int i=idx;i<nums.size();i++)
     {
         result.push_back(nums[i]);
         backtracking(ans,result,nums,i+1);
         result.pop_back();
     }
 }
Esempio n. 16
0
 void backtracking(int start, vector<vector<int>>& res, vector<int>& temp) {
     int n = temp.size();
     if(start == n - 1) {
         res.push_back(temp);
     }
     for(int i = start; i < n; i++) {
         swap(temp[start], temp[i]);
         backtracking(start + 1, res, temp);
         swap(temp[start], temp[i]);
     }
 }
 bool backtracking(string &s, int i, string &p, int j) {
     if(i == 0 && j == 0) return true;
     if(i != 0 && j == 0) return false;
     if(i == 0 && j != 0) {
         if(p[j-1] == '*')
             return backtracking(s, i, p, j-2);
         else
             return false;
     }
     if(s[i-1] == p[j-1] || p[j-1] == '.')
         return backtracking(s, i-1, p, j-1);
     else if(p[j-1] == '*') {
         if(backtracking(s, i, p, j-2)) // 不需要p[j-1]
             return true;
         if(p[j-2] == '.' || p[j-2] == s[i-1])  // s[i-1] matched
             return backtracking(s, i-1, p, j);
         return false;
     }
     return false;
 }
Esempio n. 18
0
 vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
     vector<vector<int>> res;
     if (candidates.size() == 0)
         return res;
     
     vector<int> aidVec;
     //这里不用sort()也可以。
     backtracking(candidates, target, res, aidVec, 0);
     
     return res;
 }
Esempio n. 19
0
void Sudoku::GiveQuestion()
{
	srand(time(NULL));

	const int *pTemplate = sudoku_template[rand() % cnt_template];
	int question[81], trans[10] = { 0 };

	/// random
	for (int i = 1; i <= 9; i++)
	{
		int num;

		do
		{
			num = rand() % 9 + 1;
		}while(trans[num]);

		trans[num] = i;
	}
	/// fill
	for (int i = 0; i < 81; i++)
		question[i] = trans[pTemplate[i]];
	/// dig
	for (int c = 0; c < 55; c++)
	{
		int pos;

		memcpy(table, question, sizeof(table));
		do
		{
			pos = rand() % 81;
		} while(table[pos] == EMPTY_CELL);

		table[pos] = EMPTY_CELL;

		Init();
		Analyze();
		backtracking(0);

		if (status == ONE_SOULUTION)
			memcpy(question, table, sizeof(question));
	}

	/*for (int i = 0; i < 9; i++)
	{
		for (int k = 0; k < 9; k++)
		{
			if (!k) printf("%d", question[i*9+k]);
			else printf(" %d", question[i*9+k]);
		}
		putchar('\n');
	}*/
}
Esempio n. 20
0
main()
{
	int num, test, iterator;
	printf("Enter no. of tests\n");
	scanf_s("%d", &test); //Scanning the number of tests
	for (iterator = 0; iterator < test; iterator++)
	{
		printf("Enter number\n");
		scanf_s("%d", &num); //Scanning the number
		backtracking(num);
	}
}
Esempio n. 21
0
double el_sem_naive::update_dual(double tol, int max_iter)
{

    //pre-allocate memory for gradient, hessian and update
    vec grad(v_ + (v_ *(v_ + 1) )/ 2 );
    mat hessian(v_ + (v_ *(v_ + 1) )/ 2 ,v_ + (v_ *(v_ + 1) )/ 2 );
    vec update(v_ + (v_ *(v_ + 1) )/ 2 );
    grad.zeros();
    hessian.zeros();
    update.zeros();

    // backtracking parameters
    double backtracking_scaling_const = .4;
    int back_tracking_counter;
    int max_back_track = 20; // steps required to scale update by 1e-8

    while(conv_crit_ > tol && counter_ < max_iter) {


        // build in backtracking if necessary
        set_gradient_hessian(grad, hessian);

        // back tracking line search

        update = solve(hessian, grad);

        //back track to ensure everything is greater than 1/n
        back_tracking_counter = 0;
        while(!backtracking(update) && back_tracking_counter < max_back_track) {
            update *= backtracking_scaling_const;
            back_tracking_counter++;
        }
        //if back tracking does not terminate because of max iterations update
        //else terminate
        if(back_tracking_counter < max_back_track) {
            dual_ -= update;
        } else {
            return -99999;
        }


        conv_crit_ = norm(grad ,2);
        counter_++;
    }

    d_ = (constraints_.t() * dual_) + 1.0;
    if(conv_crit_ < tol) {
        return -sum(log(n_ * d_));
    } else {
        return -999999999;
    }

}
Esempio n. 22
0
int obtemMaiorParticao() {
        int melhorSolucaoEmN = 0;
        for (int i = 0; i < N; i++) {
                melhor = 0;
                backtracking(i, 0);
                if (melhor > melhorSolucaoEmN)
                        melhorSolucaoEmN = melhor;
                if (melhorSolucaoEmN == N)
                        break;
        }
        return melhorSolucaoEmN;
}
Esempio n. 23
0
int main() {
	bool first = true;
	while (scanf("%d", &k) && k > 0) {
		if (!first)
			puts("");
		first = false;

		for (int i = 0; i < k; i++)
			scanf("%d", &conjunto[i]);
		backtracking(0, 0, false);
	}
}
Esempio n. 24
0
void Sudoku::backtracking(int cur)
{
	if (cur == 81)
	{
		if (status == ONE_SOULUTION) status = MULTI_SOLUTION;
		else if (status == UNDETERMINED)
		{
			status = ONE_SOULUTION;

			memcpy(answer, table, sizeof(answer));
		}

		return;
	}

	while(cur < 81 && table[cur])
		cur++;

	if (cur == 81)
	{
		backtracking(cur);
		return;
	}

	int x = cur / 9, y = cur % 9;
	for (int i = 1; i <= 9 && status != MULTI_SOLUTION; i++)
	{
		if (x_used[x][i] || y_used[y][i] || section_used[section_map[cur]][i]) continue;

		x_used[x][i] = y_used[y][i] = section_used[section_map[cur]][i] = true;
		table[cur] = i;

		backtracking(cur+1);

		table[cur] = EMPTY_CELL;
		x_used[x][i] = y_used[y][i] = section_used[section_map[cur]][i] = false;
	}
}
Esempio n. 25
0
 void backtracking(vector<vector<int>> &result,vector<int>ans,int last,int n,int k)
 {
     if(k==0)
     {
         result.push_back(ans);
     }
     for(int i=last+1;i<=n;i++)
     {
         ans.push_back(i);
         backtracking(result,ans,i,n,k-1);
         ans.pop_back();
     }
     
 }
void backtracking(int n, int open, int close, string str, vector<string>& res)
{
    if (close == n)
    {
        res.emplace_back(str);
        return;
    }
    else
    {
        if (open < n)
        { 
            str += '(';
            backtracking(n, open+1, close, str, res);
            str.pop_back();
        }
        if (open > close)
        {
            str += ')';
            backtracking(n, open, close+1, str, res);
            str.pop_back();
        }
    }
}
Esempio n. 27
0
int main()
{
	path[1][2] = path[1][3] = path[1][5] = 1;
	path[2][1] = path[3][1] = path[5][1] = 1;
	path[2][5] = path[2][3] = 1;
	path[5][2] = path[3][2] = 1;
	path[5][3] = path[5][4] = 1;
	path[3][5] = path[4][5] = 1;
	path[3][4] = path[4][3] = 1;

	backtracking(0,1);

	return 0;
}
Esempio n. 28
0
//Función en la que se revisa la última lectura del sensor.
//En base a ese dato, se revisa dónde hay un cruce, donde hay una bifurcación de varios caminos, y donde hay un tope
//Finalmente, para cada caso se pushea en los Stacks la información necesario para recordar el camino
//En especial, si se llega a un tope, se llama a la función backtracking
void magia(Stack *stder,Stack *stizq,Stack *stcamino)
{
  int result=0;
  result=der+izq+ade;
  if(result>1)
  {
    push(stizq,izq);
    if(ade==0)
    {
      push(stcamino,contador);
      contador=0;
      push(stcamino,contador);
      push(stcamino,-2);
      
      push(stder,0);
    } 
    else
    {
      push(stcamino,contador);
      contador=0;
      push(stcamino,contador);
      
      push(stder,der);
    } 

  }
  if(ade==0&&result==1)
  {
    if(izq==1)
    {
      push(stcamino,contador);
      push(stcamino,-1);
      contador=0;
    }
    if(der==1)
    {
      push(stcamino,contador);
      push(stcamino,-2);
      contador=0;
    }   
  }    
  if(result==0)
  {
    push(stcamino,contador);
    contador=0;
    backtracking(stder,stizq,stcamino);
  }       
}
 void backtracking(int start, int m, int n, vector<bool>& visited, int& len){
     if(len >= m)
         rslt++;
     if(len == n)
         return ;
     for(int i = 1; i <= 9; i++){
         int jump = jumps[start][i];
         if(!visited[i] && (jump == 0 || visited[jump])){
             len++;
             visited[i] = true;
             backtracking(i, m, n, visited, len);
             visited[i] = false;
             len--;
         }
     }
 }
Esempio n. 30
0
 void backtracking(vector<int>& nums, int start,int k, vector<int>& solu){
     if (k>0){
         for (int i=start;i<nums.size();++i){
             solu.push_back(nums[i]);
             if (nums.size()-start>=k){
                 backtracking(nums, i+1,k-1,solu);
             };
             solu.pop_back();
         };
     }else if (k==0){
         for (int x=0;x<ret.size();++x){
             if (ret[x]==solu) return ;
         };
         ret.push_back(solu);
     };
 };