Backtracking

Backtracking sem backjumping.
Backtracking com backjumping.

Backtracking é um tipo de algoritmo que representa um refinamento da busca por força bruta,[1] em que múltiplas soluções podem ser eliminadas sem serem explicitamente examinadas. O termo foi cunhado pelo matemático estado-unidense D. H. Lehmer na década de 1950.

O procedimento é usado em linguagens de programação como Prolog. Uma busca inicial em um programa nessa linguagem segue o padrão busca em profundidade, ou seja, a árvore é percorrida sistematicamente de cima para baixo e da esquerda para direita. Quando essa pesquisa falha, ou é encontrado um nodo terminal da árvore, entra em funcionamento o mecanismo de backtracking. Esse procedimento faz com que o sistema retorne pelo mesmo caminho percorrido com a finalidade de encontrar soluções alternativas.

Um exemplo de algoritmo de Backtracking está representado abaixo:

bool acabou = FALSE;

backtrack(int a[], int k, int n) {
	int c[MAXCANDIDATOS];  /* Candidatos para a próxima posição */
	int ncandidatos;       /* Número de candidatos para a próxima posição */
	int i;                 /* Contador */
	
	if (e_uma_solucao(a, k, n)) {
		processar_solucao(a, k, n);
	} else {
		k = k + 1;
		construir_candidatos(a, k, n, c, &ncandidatos);
		for (i=0; i<ncandidatos; i++) {
			a[k] = c[i];
			backtrack(a, k, n);
			if (acabou) return;
		}
	}
}

As principais aplicações desse tipo de algoritmo são para a construção de todos os 2^n subconjuntos de um conjunto S, com n elementos e todas as permutações desse conjunto. Abaixo seguem as sub-rotinas para cada situação, na linguagem C:

Construção de todos os subconjuntos

e_uma_solucao(int a[], int k, int n) {
	return (k == n);
}

construir_candidatos(int a[], int k, int n, int c[], int *ncandidatos) {
	c[0] = TRUE;
	c[1] = FALSE;

	*ncandidatos = 2;
}

processar_solucao(int a[], int k) {
	int i; /* Contador */

	printf("{");
	for (i=1; i<=k; i++)
		if (a[i] == TRUE)
			printf(" %d", i);

	printf(" }\n");
}

Agora, é necessário chamar a função backtrack com os argumentos certos, sendo backtrack(a, 0, n).

Construção de todas as permutações

construir_candidatos(int a[], int k, int n, int c[], int *ncandidatos) {
	int i;  /* Contador */
	bool in_perm[NMAX];   /* Quem já está na permutação? */

	for (i=1; i<NMAX; i++) in_perm[i] = FALSE;
	for (i=1; i<k; i++) in_perm[ a[i] ] = TRUE;

	*ncandidatos = 0;

	for (i=1;i<=n;i++)
		if (in_perm[i] == FALSE) {
			c[ *ncandidatos] = i;

			*ncandidatos = *ncandidatos+1;
		}
}

processar_solucao(int a[], int k) {
	int i; /* Contador */

	for (i=1; i<=k; i++)
	printf(" %d", a[i]);

	printf("\n");
}

e_uma_solucao(int a[], int k, int n) {
	return (k == n);
}

Novamente, deve-se chamar a função backtrack da forma backtrack(a, 0, n).

Referências

Ícone de esboço Este artigo sobre programação de computadores é um esboço. Você pode ajudar a Wikipédia expandindo-o.

Read other articles:

US television news program Special ReportAlso known asSpecial Report with Bret BaierGenrePolitical news and talkPresented by Bret Baier (2009–present) Country of originUnited StatesOriginal languageEnglishNo. of seasons25ProductionProduction locationsWashington, D.C.Camera setupMulti-cameraRunning time60 minutesOriginal releaseNetworkFox News ChannelReleaseJanuary 26, 1998 (1998-01-26) –present Special Report with Bret Baier (formerly Special Report with Brit Hume) is an America...

 

Giải thưởng Hội Điện ảnh Việt Nam lần thứ 3 ← Lần 2 (1995) · Lần 3 (1996) · Lần 4 (1997) → Địa điểmHà Nội, Việt NamThành lập1993Sáng lậpHội điện ảnh Việt NamKết thúc2003Kế thừaGiải Cánh diềuGiải thưởng32Ngày tổ chức1996Ngôn ngữTiếng Việt Cổng thông tin Điện ảnh Giải thưởng Hội Điện ảnh Việt Nam 1995 được tổ chức vào năm 1996 là lần thứ ...

 

Shopping mall in Texas, U.S.Collin Creek MallOutside of the Collin Creek Mall in 2019LocationPlano, Texas, U.S.Opening dateJuly 29, 1981; 42 years ago (1981-07-29)Closing dateJuly 31, 2019; 4 years ago (2019-07-31)OwnerCenturion AmericanNo. of stores and services0No. of anchor tenants5 (0 open, 5 vacant)No. of floors2Websitecollincreekmall.com Collin Creek Mall was a two-level, enclosed regional mall in Plano, Texas opened in 1981 and closed for redevelopme...

Campeonato Sul-Americano de Voleibol Masculino Sub-21 de 1984 Voleibol Informações gerais País-sede Bucaramanga Colômbia Período 09-15 de setembro Participantes 7 Premiações Campeão Brasil (5º título) Estatísticas ◄◄ Campeonato Sul-Americano de Voleibol Masculino Sub-21 de 1982 Campeonato Sul-Americano de Voleibol Masculino Sub-21 de 1986 ►► O Campeonato Sul-Americano de Voleibol Masculino Sub-21 de 1984 é a sétima edição do Campeonato Sul-Americano de Voleibol Mas...

 

← 4 5 6 → -1 (عدد) 0 1 2 3 4 5 6 7 8 9 → قائمة الأعداد — عدد صحيح ← 0 10 20 30 40 50 60 70 80 90 → كمي خمسة ترتيبي 5(خامس) التحليل 5 أرقام رومانية V نظام العد ثنائي 1012 ثلاثي 123 رباعي 114 خماسي 105 سداسي 56 ثماني 58 ثنائي عشر 512 سداسي عشر 516 عشريني 520 سداسي مربع 536 لغات تعديل مصدري - تعديل     لمعانٍ أخرى،...

 

Greek multi-sport club based in Nea Filadelfeia, Athens AEK redirects here. For their football team, see AEK FC. For other uses, see AEK (disambiguation). ‹ The template below (Infobox sports team) is being considered for merging. See templates for discussion to help reach a consensus. › A.E.KFull nameΑθλητική Ένωσις ΚωνσταντινουπόλεωςAthlitikí Énosis Konstantinoupόleos(Athletic Union of Constantinople)NicknamesVasílissa (Queen)Énosis (Union)...

Cet article concerne le référendum du 23 juin 2016. Pour la procédure de retrait du Royaume-Uni de l'Union européenne, voir Procédure de retrait du Royaume-Uni de l'Union européenne. 2011 Référendum sur l'appartenance du Royaume-Uni à l'Union européenne 23 juin 2016 Type d’élection Référendum Corps électoral et résultats Inscrits 46 501 241 Votants 33 578 016   72,21 % Votes exprimés 33 551 983 Résultat par zone de vote Le ...

 

Paucituberculata TaksonomiKerajaanAnimaliaFilumChordataKelasMammaliaOrdoPaucituberculata Ameghino, 1894 Famili dan genus Caenolestidae Caenolestes Lestoros Rhyncholestes lbs Paucituberculata adalah ordo marsupialia Amerika Selatan. Meskipun saat ini mereka hanya terdiri atas tujuh spesies oposum tikus, ordo ini sebelumnya jauh lebih beragam, dengan lebih dari 60 spesies yang telah punah berdasarkan catatan fosil, terutama dari zaman Oligosen akhir hingga zaman Miosen awal.[1][2 ...

 

Lista de los Trabajadores Israelíesרְשִׁימָת פּוֹעַלֵי יִשְׂרָאֵל Presidente David Ben-GuriónFundación 14 de julio de 1965Disolución 23 de enero de 1968Escisión de MapaiIdeología SocialdemocraciaSecularismoSionismo socialistaPosición CentroizquierdaSucesor Partido Laborista IsraelíSede Tel AvivPaís Israel[editar datos en Wikidata] Rafi (en hebreo: רַפִי‎ acrónimo de Reshimat Poalei Yisrael (en hebreo: רְשִׁימָת פּוֹעַלֵ

17th-century Indian writer and poet Unnayi WarrierBorn17th/18th century CE (estimated)Irinjalakuda, Kerala, IndiaOccupationPoet, writerNationalityIndianNotable worksNalacharitham Unnayi Warrier was a poet, writer, scholar, and dramatist who lived in Kerala, India during the 17th/18th century. He is best known for his chef-d'oeuvre Nalacharitham aattakatha and is known to have made significant contributions to the art of Kathakali, the classical dance-drama form of Kerala. Biography There are ...

 

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Asociación de Scouts de Bolivia – news · newspapers · books · scholar · JSTOR (February 2010) (Learn how and when to remove this template message) Asociación de Scouts de BoliviaHeadquarterscalle litoral #300, CochabambaCountryBoliviaFounded1911Membership7,89...

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (مارس 2021) أبو المهنى مخارق معلومات شخصية تاريخ الميلاد القرن 8 ميلادي تاريخ الوفاة 844 م الديانة مسلم الحياة العملية المهنة موسيقي، مغني تعديل مصدري - تعديل   أبوالمهن...

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Zentrix – news · newspapers · books · scholar · JSTOR (November 2018) (Learn how and when to remove this template message) Hong Kong TV series or program ZentrixA promotional poster for Zentrix.GenreAnimationActionCreated byTony TangBenny ChowFelix IpFranc...

 

2014 studio album by The DrumsEncyclopediaStudio album by The DrumsReleasedSeptember 23, 2014GenreIndie pop, post-punk revival, dream popLabelNorman RecordsProducerThe DrumsThe Drums chronology Portamento(2011) Encyclopedia(2014) Abysmal Thoughts(2017) Singles from Encyclopedia Magic MountainReleased: July 22, 2014[1] I Can't PretendReleased: August 26, 2014[2] Encyclopedia is the third studio album of American indie pop band The Drums. It was released on September 23,...

 

Former private college in Jacksonville, Illinois, U.S. This article is about the college in Jacksonville, Illinois. For McMurry University in Abilene, Texas, see McMurry University. MacMurray CollegeTypePrivate collegeActive1846–May 2020Religious affiliationUnited Methodist ChurchPresidentBeverley RogersUndergraduates570[1]LocationJacksonville, Illinois, United StatesCampusRural, 60 acresColorsTartanMascotHighlanderWebsitewww.mac.edu MacMurray College was a private college in Jackso...

Route of S12 Legend 20.5 Horrem S19 25.4 Frechen-Königsdorf S19 28.1 Köln-Weiden West S19 29.5 Köln-Lövenich S19 33.3 Köln-Müngersdorf Technologiepark S19 35.5 Köln-Ehrenfeld S19 38.4 Köln Hansaring S6S11S19 39.2 Köln Hbf S6S11S19 40.3 Köln Messe/Deutz S6S11S19 Köln Trimbornstr. S19 Köln Airport Businesspark Köln Steinstraße 49.9 Porz (Rhein) 52.7 Porz-Wahn S19 57.2 Spich S19 60.0 Troisdorf S19 64.6 Siegburg/BonnS19 71.1 Hennef (Sieg) S19 73.0 Hennef im Siegbogen S19 75.6 Blanke...

 

This article is part of a series on theCulture of Australia Society History Language People Immigration Multiculturalism Religion Arts and literature Architecture Art Literature Comics Performing arts Dance Music Theater Pro wrestling Other Cuisine Festivals Folklore Humour Media Newspapers Radio Cinema TV Internet Mythology Sports Video gaming Symbols Flag Coat of arms Anthem Monuments World Heritage Sites Australia portalvte The performing arts in Australia are an important element of the A...

 

Craig J. Spence (October 25, 1940[1] – November 10, 1989) was an American journalist, lobbyist, and socialite who committed suicide in 1989 in the wake of a Washington Times exposé reporting on his involvement in a prostitution ring and in blackmail. Background Spence attended Syracuse University and began his journalism career working for WCBS in New York City.[2] He would eventually become a correspondent for ABC News. During the Vietnam War, he covered Southeast Asia, bu...

Goda MountainsDay Forest National Park in the Goda MountainsHighest pointElevation1,783 m (5,850 ft)at AbeydaCoordinates11°52′N 42°47′E / 11.86°N 42.79°E / 11.86; 42.79DimensionsLength24 km (15 mi)Width31 km (19 mi)Area901 km2 (348 sq mi)Geography Country DjiboutiRegionTadjourah Region The Goda Mountains lie northwest of the Gulf of Tadjoura, Tadjoura Region in Djibouti. They rise to 1,750 metres (5,740...

 

Chilean footballer (born 1981) In this Spanish name, the first or paternal surname is Canío and the second or maternal family name is Manosalva. Cristián Canío Personal informationFull name Cristián Eduardo Canío ManosalvaDate of birth (1981-05-31) 31 May 1981 (age 42)Place of birth Nueva Imperial, ChileHeight 1.76 m (5 ft 9 in)Position(s) ForwardYouth career Deportes TemucoSenior career*Years Team Apps (Gls)2002–2004 Deportes Temuco 60 (17)2002 → Ñublens...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!