15puzzle 문제를 이해하기 위해 깊이 우선 검색 및 폭이 먼저 검색에 대해 배웠습니다. 먼저 깊이 우선 검색 (DFS)에 대해 논의 해 봅시다. 깊이 우선의 목적은 시작 정점에서 가장 먼 경로를 검색하는 것이 우선 순위를 정하는 반면, 폭이 먼저 검색하는 것은 먼저 시작 정점에 가장 가까운 경로를 검색하는 것입니다. 깊이 우선 검색과 역 추적의 차이점은 무엇입니까? Baidu에서는 역 추적이 일종의 깊은 검색이라고 말하지만 차이점은 역 추적이 검색 트리를 유지하지 않는다는 것입니다. 그렇다면 광범위한 첫 번째 검색 (BFS)은 어떻습니까? 응용 프로그램은 무엇입니까? 답변 : 가장 짧은 경로, 와인 디비전 문제, 8 개의 디지털 문제 등. 요점으로 돌아가 봅시다. 그 중에서도 Dep Search는 Graph + Stack을 사용하여 구현되며 Graph + 큐를 사용하여 광범위한 검색이 구현됩니다. 코드는 다음과 같습니다.
1. "방향이없는 그래프"를 나타내는 새로운 클래스 NodirectionGraph 만들기
package com.wly.algorithmbase.datrastructure;/** * 방향없는 그래프 * @author wly * */public class nodirectiongraph {private int mmaxsize; // 그래프 개인 그래프 Vertex [] vertexlist; // vertex array array hannectire 간의 vertex array; 정점 개인 int nvertex; // 현재 저장된 정점의 수는 공개적으로 저장된 공개 nodirectiongraph (int maxsize) {mmaxsize = maxsize; vertexlist = new GraphVertex [mmaxsize]; indicatorMat = new int [mmaxsize] [mmaxsize]; nvertex = 0; int hetize matrrix matrrix matrix matrix matrix matrix j = 0; {System.out.println ( "--- 삽입 실패, 정점의 수가 상한에 도달했습니다!");}}/*** 인접성 행렬을 수정하고 새 모서리를 추가하고 새 가장자리* @param start*/public void addedge (int start, ind] 인접 행렬*/public void printIndicatorMat () {for (int [] line : indicatorMat) {for (int i : line) {system.out.print (i + "" ");} system.out.println ()}}}}}}}}}}* @param vertexindex index는 트래버스의 시작 지점을 나타냅니다. 그래프 */public void dfs (int vertexindex) {arraystack stack = new arraystack (); // 1. 검색 요소를 스택 vertexlist [vertexIndex]에 추가하십시오. while (! stack.isempty ()) {// 스택을 계속 누르고 스택이 비어있을 때까지 스택을 누르고 스택을 꺼내십시오 (검색 요소가 스택을 팝업하지 않음 (NextVertexIndex! = -1) {vertexlist [nextVertexIndex] .setVisted (true); stack.push (nextVertexIndex);}; {stack.pop ();} // 현재 상단 요소에 다른 트레이버 노드가 포함되어 있는지 (! stack.isempty ()) {nextVertexIndex = getnextVertexIndex (stack.peek ())를 포함하는지 여부를 검색합니다. getNextVertexIndex (int column) {for (int i = 0; i <indicatorMat [column] .length; length; i ++) {if (indicatorMat [컬럼] [i] == 1 &&! vertexlist [i] .isvisited ()) {return i;}} return -1; 즉, 그래프*/public void bfs (int vertexIndex) {chainqueue queue = new Chainqueue (); vertexlist [vertexindex] .setvisited (true); queue.insert (vertexindex (vertexindex)); while (! queue.isempty ()) {if (nextVertexIndex! = -1) {vertexlist [nextVertexIndex] .setvisited (true); queue.insert (new QueueNode (nextVertexIndex));} else {queue.remove (); getNextVertexIndex (queue.peek (). data); queue.printelems ();}}}}2. 그런 다음 배열로 시뮬레이션되는 배열이 있습니다.
패키지 com.wly.algorithmbase.datrastructure;/***배열 사용 스택 구조*@author wly**/public class arraystack {private int [] tarray; private int topindex = -1; // 스택의 현재 상단 요소의 인덱스 위치를 나타냅니다. 일반 배열 ***/tarray = new int [paction_step];}/***상단 요소를 팝업하는 메소드*@return*/public int pop () {if (isempty ()) {system.out.println ( "오류, 스택의 요소가 비어 있고 팝 팝"); return -1;} else {int i = tarray [topIndex]; tarray [topIndex-] = -1; // 팝 요소 반환 i;}}/*** 스택에 요소를 삽입* @param t*/public void push (int t) {// 스택이 가득 찼는 지 (topindex ==) new int [tarray.length + capacity_step]; for (int i = 0; i <tarray.length; i ++) {temparray [i] = tarray [i];} tarray = temparray; temparray = null;} else {topindex ++; tarray [topindex] = t;}}/** * 스택의 상단 요소를 얻지 못하지만 (@ethin */public int) {if (isempty ()) {system.out.println ( "오류, 스택의 요소가 비어 있고, 엿보기가 비어 있습니다. printelems () {for (int i = 0; i <= topindex; i ++) {system.out.print (tarray [i]+"");} system.out.println ();}}3. 링크 된 목록으로 시뮬레이션 된 대기열의 체인 큐
package com.wly.algorithmbase.datrastructure;/** * 링크 된 목록을 사용하여 대기열 * * @author wly * */public class chainqueue {private queuenode head; // 큐 개인 queuenode 꼬리의 헤드를 가리 킵니다. 대기열의 꼬리에 새 노드*/public void insert (queuenode node) {// 물론, 당신은 이것을 쓸 수 있습니다. tail.prev = node if (head == null) {head = node; tail = head;} else {node.next = tail.prev = node; // head.prev가 텅 비어 있는지 확인하십시오. 노드;} size ++;}/*** 큐 헤드 노드를 제거*/public queuenode remove () {if (! isempty ()) {queuenode temp = head; head = head.prev; size-; return} else {System.out.println ( "예외 작동, 현재 퀘이트는 비어 있습니다!" 빈 * * @return */public boolean isempty () {if (size> 0) {return false;} else {return true;}}/** * 큐의 첫 번째 노드를 반환하지만 제거하지 않지만 */public queuenode peek () {if (! isempty ()) {return.out.out.println (); 현재 대기열이 비어 있습니다! "); return null;}}/*** 대기열 크기를 반환합니다** @return*/public int size () {return size;}/*** 대기열의 인쇄 요소*/public void printelems () {queuenode tempnode = head; while (tempnode! = null) {tempnata +" "); tempnode = tempnode.prev;} system.out.println ();}}/** * 노드 클래스 * * @author wly */class queuenode {queuenode prev; queuenode next; int data; public retud data;} public getdata ()}}}} setData (int data) {this.data = data;}@public string toString () {// todo 자동 생성 메소드 스텁 SUPER.TOSTRING (); return data + "";}}4. test test_bfs_dfs
package com.wly.algorithmbase.search; import com.wly.algorithmbase.datrastructure.graphvertex; import com.wly.algorithmbase.datrastructure.nodipectionGraph;/** * 그래프 기반 Depth-First Search * @Author */public class test_bfs_dfs {problic voide (problic voide) {// 테스트 데이터 초기화 데이터 nodiprectiongraph 그래프 = new NodirectionGraph (7); Graph.AddVertex (새 그래프버 텍스 ( "a")); graph.addvertex (새 그래프버 텍스 ( "b")); graph.addvertex (new GraphVertex ( "c")); graph.addvertex ( "d"); GraphVertex ( "e"); graph.addvertex (new GraphVertex ( "f")); graph.addvertex ( "g"); graph.addedge (0, 1); Graph.AdDedge (0, 2); Graph.Addedge (1, 3); Graph.Addedged (1, 4); AdddDedged (3, 6); 5); System.out.println ( "-그래프의 인접 행렬-"); Graph.PrintIndicAtorMat (); // 딥 검색 시스템을 테스트합니다. GraphVertex ( "b"); graph.addvertex (new GraphVertex ( "c")); Graph.AddVertex ( "d")); Graph.AddVertex ( "e"); graph.addvertex (new GraphVertex ( "F")); Graph.addverTex (new GraphVertex ( "g"); Graph.AddEdge (0, 1); Graph.AddEdge (0, 2); Graph.AddEdge (1, 3); Graph.AddEdge (1, 4); Graph.AdDedge (3, 6); Graph.AdDedge (2, 5); System.out.println ( "-wadth Priority 검색-");여기서 테스트 된 그래프 구조는 다음과 같습니다.
작업 결과는 다음과 같습니다.
--Adjacent matrix of graph-- 0 1 1 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
여기서 우리는 위의 깊은 검색과 광범위한 검색의 실행 결과를 설명해야합니다. 여기서 0, 1, 2, 3 ... 각각 A, B, C, D에 해당합니다 ... 약간 혼란 스럽습니다. 용서 해주세요 ~~
오 ~~~
요약
위의 것은 그래프 기반 깊이 우선 검색의 Java 프로그래밍 구현 및 광선 검색 전체 코드에 대한이 기사의 모든 내용입니다. 모든 사람에게 도움이되기를 바랍니다. 관심있는 친구는이 사이트의 다른 관련 주제를 계속 참조 할 수 있습니다. 단점이 있으면 메시지를 남겨 두십시오. 이 사이트를 지원해 주신 친구들에게 감사드립니다!