zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    bzoj2946 [Poi2000]公共串(SA,SAM)
    77 最长公共子序列
    C++ lower_bound 与 upper_bound 函数
    76 最长上升子序列
    75 寻找峰值
    C++标准输入问题
    74 第一个错误的代码版本
    73 前序遍历和中序遍历树构造二叉树
    72 中序遍历和后序遍历树构造二叉树
    71 二叉树的锯齿形层次遍历
  • 原文地址:https://www.cnblogs.com/fxzemmm/p/14847912.html
Copyright © 2011-2022 走看看