蓝桥杯之迷宫
程序员文章站
2022-05-20 22:51:27
...
package LanQiao;
import java.util.LinkedList;
import java.util.Queue;
public class LanQiao67 {
public static void main(String[] args) {
int[][] nums = {
{0, 0},
{0, 0}
};
bfs(nums);
}
public static void bfs(int[][] nums){
Queue<NextNode> queue = new LinkedList<>();
boolean[][] isVisted = new boolean[nums.length][nums[0].length];
queue.add(new NextNode(0, 0, ""));
while(!queue.isEmpty()){
NextNode nn = queue.poll();
int row = nn.row;
int column = nn.column;
isVisted[row][column] = true;
if(row == nums.length - 1 && column == nums[0].length - 1){
System.out.println(nn.path);
}else{
if(row - 1 >= 0 && nums[row - 1][column] == 0 && !isVisted[row - 1][column]){
NextNode n = new NextNode(row - 1, column, nn.path + "U");
queue.add(n);
}
if(column - 1 >= 0 && nums[row][column - 1] == 0 && !isVisted[row][column - 1]){
NextNode n = new NextNode(row, column - 1, nn.path + "L");
queue.add(n);
}
if(row + 1 < nums.length && nums[row + 1][column] == 0 && !isVisted[row + 1][column]){
NextNode n = new NextNode(row + 1, column, nn.path + "D");
queue.add(n);
}
if(column + 1 < nums[0].length && nums[row][column + 1] == 0 && !isVisted[row][column + 1]){
NextNode n = new NextNode(row, column + 1, nn.path + "R");
queue.add(n);
}
}
}
}
}
class NextNode{
int row;
int column;
String path;
public NextNode(int row, int column, String path){
this.row = row;
this.column = column;
this.path = path;
}
}
上一篇: 幸运数 蓝桥杯 深搜
下一篇: 简单的四色问题