Skip to content

Instantly share code, notes, and snippets.

@shui
Created January 9, 2018 01:15
Show Gist options
  • Save shui/317e931e6d99a0669705b735219509e0 to your computer and use it in GitHub Desktop.
Save shui/317e931e6d99a0669705b735219509e0 to your computer and use it in GitHub Desktop.
BFS demo
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
}
boolean bfs(Node start, Node end) {
LinkedList<Node> queue = new LinkedList<>();
Node vn; // 队列下一个节点
Node vw; // 相邻节点
int len = end.x - start.x + 1;
boolean[][] visit = new boolean[len][len];
int[][] dir = new int[][]{
{-1, 0}, {1, 0}, {0, -1}, {0, 1} // 上下左右
};
queue.push(start);
visit[start.x][start.y] = true;
while (!queue.isEmpty()) {
vn = queue.pop();
for (int i = 0; i < len; i++) {
vw = new Node(vn.x + dir[i][0], vn.y + dir[i][1], len);
if (!vw.isValid()) {
continue;
}
if (vw.equals(end)) {
return true; // 找到终点,返回
}
if (!visit[vw.x][vw.y]) {
visit[vw.x][vw.y] = true;
}
}
}
return false;
}
class Node {
int x, y, len;
Node(int x, int y, int len) {
this.x = x;
this.y = y;
this.len = len;
}
boolean equals(Node node) {
return this.x == node.x && this.y == node.y;
}
boolean isValid() {
return x < len && x >= 0 &&
y < len && y >= 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment