java bfs 迷宫例子_51-迷宫(一)- java版dfs和bfs
一天蒜頭君掉進了一個迷宮里面,蒜頭君想逃出去,可憐的蒜頭君連迷宮是否有能逃出去的路都不知道。
看在蒜頭君這么可憐的份上,就請聰明的你告訴蒜頭君是否有可以逃出去的路。
輸入格式
第一行輸入兩個整數?nn?和?mm,表示這是一個?n \times mn×m?的迷宮。
接下來的輸入一個?nn?行?mm?列的迷宮。其中?'S'?表示蒜頭君的位置,'*'表示墻,蒜頭君無法通過,'.'表示路,蒜頭君可以通過'.'移動,'T'表示迷宮的出口(蒜頭君每次只能移動到四個與他相鄰的位置——上,下,左,右)。
輸出格式
輸出一個字符串,如果蒜頭君可以逃出迷宮輸出"yes",否則輸出"no"。
數據范圍
1 \le n, m \le 101≤n,m≤10。
輸出時每行末尾的多余空格,不影響答案正確性
樣例輸入1復制
3 4
S**.
..*.
***T
樣例輸出1復制
no
樣例輸入2復制
3 4
S**.
....
***T
樣例輸出2復制
yes
bfs:? 就是遍歷周圍的格子,能走的放入到一個Stack里面,然后放完,就一次去取,一層一層的取,注意要用一個 visit判斷是否以前放入了,一旦重復放入那就會死循環。
import java.util.Scanner;
import java.util.Stack;
public class Main{
public static String mp[] = new String[11];
public static int visit[][] = new int[11][11];
public static int ans = 0;
public static int n, m;
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
n = cin.nextInt();
m = cin.nextInt();
for(int i = 0; i < n; i++) {
mp[i] = cin.next();
//System.out.println(i + mp[i]);
}
//System.out.println("-----");
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(mp[i].charAt(j) == 'S') {
dfs(i,j);
break;
}
}
}
if(ans == 0) {
System.out.println("no");
}
else {
System.out.println("yes");
}
}
public static void dfs(int x0, int y0) {
node no = new node(x0, y0);
Stack stack = new Stack();
stack.add(no);
visit[x0][y0] = 1;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
while(!stack.empty()) {
node nd = stack.pop();
for(int i = 0; i < 4; i++) {
int x = nd.x + dx[i];
int y = nd.y + dy[i];
if(x >= 0 && x < n && y >= 0 && y < m &&
visit[x][y] == 0 && mp[x].charAt(y) != '*') {
if(mp[x].charAt(y) == 'T') {
ans = 1;
return ;
}
else {
node temp = new node(x, y);
stack.add(temp);
visit[x][y] = 1;
}
}
}
}
}
}
class node{
int x, y;
node(){
}
node(int x0, int y0){
this.x = x0;
this.y = y0;
}
}
dfs:
import java.util.Scanner;
public class Main1{
public static String mp[] = new String[11];
public static int[][] visit = new int[11][11];
public static int n, m, ans;
public static int dx[] = {0, 0, 1, -1};
public static int dy[] = {1, -1, 0, 0};
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
n = cin.nextInt();
m = cin.nextInt();
for(int i = 0; i < n; i++) {
mp[i] = cin.next();
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(mp[i].charAt(j) == 'S') {
visit[i][j] = 1;
dfs(i, j);
break;
}
}
}
if(ans == 1) {
System.out.println("yes");
}
else {
System.out.println("no");
}
}
public static void dfs(int x0, int y0) {
if(mp[x0].charAt(y0) == 'T') {
ans = 1;
return ;
}
for(int i = 0; i < 4; i++) {
int x = x0 + dx[i];
int y = y0 + dy[i];
if(x >= 0 && x < n && y >= 0 && y < m
&& visit[x][y] == 0 && mp[x].charAt(y) != '*') {
visit[x][y] = 1;
dfs(x, y);
visit[x][y] = 0;
}
}
}
}
總結
以上是生活随笔為你收集整理的java bfs 迷宫例子_51-迷宫(一)- java版dfs和bfs的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网络安全先驱传奇大佬自杀了,他的一生足够
- 下一篇: 挂号显示服务器异常是什么情况,支付宝挂号