1. 程式人生 > >深度優先演算法實現程式碼

深度優先演算法實現程式碼

近來發現網上寫Java的原始碼不是很多,現在把深度優先搜尋的原始碼附上

本原始碼主要針對迷宮問題

import java.util.Scanner;

import java.util.Stack;


public class Main{
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
int[][] map = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
map[i][j] = sc.nextInt();
}
}
// 深度優先搜尋-->與棧相關
Stack<Node> stack = new Stack<Node>();
Node start = new Node(0, 0);
Node end = new Node(m - 1, n - 1);
int[][] visted = new int[m][n];
int[][] dir = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };
stack.push(start);
while (!stack.isEmpty()) {
Node per = stack.peek();
boolean flag = false;
if (per.x == end.x && per.y == end.y) {
break;
} else {
for (int i = 0; i < 4; i++) {
Node nbr = new Node(per.x + dir[i][0], per.y + dir[i][1]);
if (nbr.x >= 0 && nbr.x < m && nbr.y >= 0 && nbr.y < n && map[nbr.x][nbr.y] == 0
&& visted[nbr.x][nbr.y] == 0) {
stack.push(nbr);
flag = true;
visted[nbr.x][nbr.y] = 1;
break;
}
}
if (flag) {
continue;
}
stack.pop();
}
}
if (!stack.isEmpty()) {
Stack<Node> result = new Stack<Node>();
while (!stack.isEmpty()) {
result.push(stack.pop());
}
while (!result.isEmpty()) {
System.out.printf("(" + result.peek().x + "," + result.peek().y + ")");
result.pop();
}
} else {
System.out.println("NO");
}
}
}


class Node {
int x, y;


public Node(int x, int y) {
this.x = x;
this.y = y;
}
}