• CodeForces


    在这里插入图片描述
    在这里插入图片描述
    题目链接

    BFS 注意起点和终点相同的情况

    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.Scanner;
    
    public class Main{
        static String s0,s1;
        static String[] str = {"LU","U","RU","R","RD","D","LD","L"};
        static int[][] next = {{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0}};
        public static void main(String[] args){
            Scanner sc = new Scanner(System.in);
            while (sc.hasNext()){
                s0 = sc.next();
                s1 = sc.next();
                bfs();
            }
        }
        public static void bfs(){
            int x0 = Integer.valueOf(s0.charAt(0)-'a');
            int y0 = Integer.valueOf(s0.substring(1));
            int x1 = Integer.valueOf(s1.charAt(0)-'a');
            int y1 = Integer.valueOf(s1.substring(1));
            Queue<Node> queue = new LinkedList<>();
            boolean[][] flag = new boolean[10][10];
            flag[x0][y0] = true;
            queue.add(new Node(x0,y0,0,""));
            if(x0==x1&&y0==y1){
                System.out.println(0);
                return;
            }
            while(queue.size()>0){
                Node no = queue.poll();
                int x = no.x;
                int y = no.y;
                int s = no.s;
                String b = no.book;
                for(int i=0;i<8;i++){
                    int ts = s+1;
                    int tx = x+next[i][0];
                    int ty = y+next[i][1];
                    String tb = b+str[i]+"
    ";
                    if(tx<0||tx>=8||ty<1||ty>8) continue;
                    if(flag[tx][ty]) continue;
                    flag[tx][ty] = true;
                    if(tx==x1&&ty==y1){
                        System.out.println(ts);
                        System.out.println(tb);
                        return;
                    }
                    queue.add(new Node(tx,ty,ts,tb));
                }
            }
        }
    }
    class Node{
        int x,y,s;
        String book;
        Node(int x,int y,int s,String book){
            this.x = x;
            this.y = y;
            this.s = s;
            this.book = book;
        }
    }
    
  • 相关阅读:
    Leetcode 剑指 Offer 27(二叉树的镜像)
    Leetcode 1022从根到叶的二进制之和
    Leetcode 993二叉树的堂兄弟节点
    Leetcode 965单值二叉树
    Leetcode 938 二叉搜索树的范围和
    hdu 2082 找单词
    母函数模板
    hdu 1398 Square Coins
    hdu 1085 Holding Bin-Laden Captive!
    hdu 1028 Ignatius and the Princess III
  • 原文地址:https://www.cnblogs.com/fxzemmm/p/14847912.html
Copyright © 2020-2023  润新知