Filip_Markoski

[ADSx] - Board (Fast)

Jan 23rd, 2018
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.84 KB | None | 0 0
  1. import java.util.*;
  2. import java.util.stream.IntStream;
  3.  
  4. public class Board {
  5.  
  6.     public static void main(String args[]) {
  7.         String text = "100 100\n" +
  8.                 "2 100 50 50";
  9.         //Scanner scanner = new Scanner(text);
  10.         Scanner scanner = new Scanner(System.in);
  11.         int rows = scanner.nextInt();
  12.         int columns = scanner.nextInt();
  13.         scanner.nextLine();
  14.  
  15.         // Minus one for all because we iterate starting from 0
  16.         int x1 = scanner.nextInt() - 1;
  17.         int y1 = scanner.nextInt() - 1;
  18.         int x2 = scanner.nextInt() - 1;
  19.         int y2 = scanner.nextInt() - 1;
  20.  
  21.         /**
  22.          * https://en.wikipedia.org/wiki/Knight%27s_graph
  23.          * https://www.geeksforgeeks.org/minimum-steps-reach-target-knight/
  24.          * */
  25.  
  26.         Integer elements[] = new Integer[(rows + 1) * (columns + 1)];
  27.         IntStream.range(0, elements.length).forEach(i -> elements[i] = i);
  28.  
  29.         //System.out.print(Arrays.toString(elements));
  30.  
  31.         Graph<Integer> graph = new Graph<>((rows + 1) * (columns + 1), elements);
  32.  
  33.         for (int i = 0; i < rows; i++) {
  34.             for (int j = 0; j < columns; j++) {
  35.                 if (i + 2 < rows && j + 1 < columns) {
  36.                     graph.addEdge(transform(i, j, columns), transform(i + 2, j + 1, columns));
  37.                 }
  38.                 if (i + 2 < rows && j - 1 >= 0) {
  39.                     graph.addEdge(transform(i, j, columns), transform(i + 2, j - 1, columns));
  40.                 }
  41.                 if (i - 2 >= 0 && j + 1 < columns) {
  42.                     graph.addEdge(transform(i, j, columns), transform(i - 2, j + 1, columns));
  43.                 }
  44.                 if (i - 2 >= 0 && j - 1 >= 0) {
  45.                     graph.addEdge(transform(i, j, columns), transform(i - 2, j - 1, columns));
  46.                 }
  47.                 if (j + 2 < columns && i + 1 < rows) {
  48.                     graph.addEdge(transform(i, j, columns), transform(j + 2, i + 1, columns));
  49.                 }
  50.                 if (j + 2 < columns && i - 1 >= 0) {
  51.                     graph.addEdge(transform(i, j, columns), transform(j + 2, i - 1, columns));
  52.                 }
  53.                 if (j - 2 >= 0 && i + 1 < rows) {
  54.                     graph.addEdge(transform(i, j, columns), transform(j - 2, i + 1, columns));
  55.                 }
  56.                 if (j - 2 >= 0 && i - 1 >= 0) {
  57.                     graph.addEdge(transform(i, j, columns), transform(j - 2, i - 1, columns));
  58.                 }
  59.             }
  60.         }
  61.  
  62.         int from = transform(x1, y1, columns);
  63.         int to = transform(x2, y2, columns);
  64.         int steps = bfsSearch(graph, from, to);
  65.         System.out.println(steps);
  66.  
  67.     }
  68.  
  69.     public static int transform(int i, int j, int n) {
  70.         return i * n + j;
  71.     }
  72.  
  73.  
  74.     public static int bfsSearch(Graph<Integer> g, int from, int to) {
  75.         Queue<Integer> nodes = new LinkedList<>();
  76.         Queue<Integer> steps = new LinkedList<>();
  77.         HashSet<Integer> visited = new HashSet<>();
  78.         nodes.add(from);
  79.         steps.add(0);
  80.         while (!nodes.isEmpty()) {
  81.             int c = nodes.poll();
  82.             int st = steps.poll();
  83.             if (visited.contains(c)) {
  84.                 continue;
  85.             }
  86.             visited.add(c);
  87.             if (c == to) {
  88.                 return st;
  89.             }
  90.             GraphNode<Integer> current = g.adjList[c];
  91.             for (GraphNode<Integer> neighbor : current.getNeighbors()) {
  92.                 nodes.add(neighbor.getIndex());
  93.                 steps.add(st + 1);
  94.             }
  95.         }
  96.         return -1;
  97.     }
  98.  
  99.     public static <T> void printMatrix(T matrix[][]) {
  100.         System.out.println("Main.");
  101.         Arrays.stream(matrix)
  102.                 .map(Arrays::toString)
  103.                 .forEach(System.out::println);
  104.     }
  105.  
  106.     public static boolean isInside(int x, int y, int N) {
  107.         if (x >= 1 && x <= N && y >= 1 && y <= N) return true;
  108.         return false;
  109.     }
  110.  
  111.     public static int minStepToReachTarget(int knightPos[], int targetPos[], int N) {
  112.         //  x and y direction, where a knight can move
  113.         int dx[] = {-2, -1, 1, 2, -2, -1, 1, 2};
  114.         int dy[] = {-1, -2, -2, -1, 1, 2, 2, 1};
  115.  
  116.         //  queue for storing states of knight in board
  117.         Queue<Cell> queue = new LinkedList<>();
  118.  
  119.         //  push starting position of knight with 0 distance
  120.         queue.add(new Cell(knightPos[0], knightPos[1], 0));
  121.  
  122.         Cell t;
  123.         int x, y;
  124.         boolean visited[][] = new boolean[N + 1][N + 1];
  125.  
  126.         //  make all cell unvisited
  127.         for (int i = 1; i <= N; i++)
  128.             for (int j = 1; j <= N; j++)
  129.                 visited[i][j] = false;
  130.  
  131.         //  visit starting state
  132.         visited[knightPos[0]][knightPos[1]] = true;
  133.  
  134.         //  loop until we have one element in queue
  135.         while (!queue.isEmpty()) {
  136.             t = queue.poll();
  137.             visited[t.x][t.y] = true;
  138.  
  139.             // if current cell is equal to target cell,
  140.             // return its distance
  141.             if (t.x == targetPos[0] && t.y == targetPos[1])
  142.                 return t.dis;
  143.  
  144.             //  loop for all reachable states
  145.             for (int i = 0; i < dx.length; i++) {
  146.                 x = t.x + dx[i];
  147.                 y = t.y + dy[i];
  148.  
  149.                 // If rechable state is not yet visited and
  150.                 // inside board, push that state into queue
  151.                 if (isInside(x, y, N) && !visited[x][y])
  152.                     queue.add(new Cell(x, y, t.dis + 1));
  153.  
  154.             }
  155.         }
  156.         return -1;
  157.     }
  158.  
  159.  
  160. }
  161.  
  162. class GraphNode<E> {
  163.     private int index;//index (reden broj) na temeto vo grafot
  164.     private E info;
  165.     private LinkedList<GraphNode<E>> neighbors;
  166.  
  167.     public GraphNode(int index, E info) {
  168.         this.index = index;
  169.         this.info = info;
  170.         neighbors = new LinkedList<GraphNode<E>>();
  171.     }
  172.  
  173.     boolean containsNeighbor(GraphNode<E> o) {
  174.         return neighbors.contains(o);
  175.     }
  176.  
  177.     void addNeighbor(GraphNode<E> o) {
  178.         neighbors.add(o);
  179.     }
  180.  
  181.  
  182.     void removeNeighbor(GraphNode<E> o) {
  183.         if (neighbors.contains(o))
  184.             neighbors.remove(o);
  185.     }
  186.  
  187.  
  188.     @Override
  189.     public String toString() {
  190.         String ret = "INFO:" + info + " SOSEDI:";
  191.         for (int i = 0; i < neighbors.size(); i++)
  192.             ret += neighbors.get(i).info + " ";
  193.         return ret;
  194.  
  195.     }
  196.  
  197.     @Override
  198.     public boolean equals(Object obj) {
  199.         @SuppressWarnings("unchecked")
  200.         GraphNode<E> pom = (GraphNode<E>) obj;
  201.         return (pom.info.equals(this.info));
  202.     }
  203.  
  204.     public int getIndex() {
  205.         return index;
  206.     }
  207.  
  208.     public void setIndex(int index) {
  209.         this.index = index;
  210.     }
  211.  
  212.     public E getInfo() {
  213.         return info;
  214.     }
  215.  
  216.     public void setInfo(E info) {
  217.         this.info = info;
  218.     }
  219.  
  220.     public LinkedList<GraphNode<E>> getNeighbors() {
  221.         return neighbors;
  222.     }
  223.  
  224.     public void setNeighbors(LinkedList<GraphNode<E>> neighbors) {
  225.         this.neighbors = neighbors;
  226.     }
  227.  
  228.  
  229. }
  230.  
  231. class Graph<E> {
  232.  
  233.     int num_nodes;
  234.     GraphNode<E> adjList[];
  235.  
  236.     @SuppressWarnings("unchecked")
  237.     public Graph(int num_nodes, E[] list) {
  238.         this.num_nodes = num_nodes;
  239.         adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
  240.         for (int i = 0; i < num_nodes; i++)
  241.             adjList[i] = new GraphNode<E>(i, list[i]);
  242.     }
  243.  
  244.     @SuppressWarnings("unchecked")
  245.     public Graph(int num_nodes) {
  246.         this.num_nodes = num_nodes;
  247.         adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
  248.         for (int i = 0; i < num_nodes; i++)
  249.             adjList[i] = new GraphNode<E>(i, null);
  250.     }
  251.  
  252.     int adjacent(int x, int y) {
  253.         // proveruva dali ima vrska od jazelot so
  254.         // indeks x do jazelot so indeks y
  255.         return (adjList[x].containsNeighbor(adjList[y])) ? 1 : 0;
  256.     }
  257.  
  258.     void addEdge(int x, int y) {
  259.         // dodava vrska od jazelot so indeks x do jazelot so indeks y
  260.         if (!adjList[x].containsNeighbor(adjList[y])) {
  261.             adjList[x].addNeighbor(adjList[y]);
  262.         }
  263.     }
  264.  
  265.     void deleteEdge(int x, int y) {
  266.         adjList[x].removeNeighbor(adjList[y]);
  267.     }
  268.  
  269.     /************************TOPOLOGICAL SORT*******************************************************************/
  270.  
  271.     void dfsVisit(Stack<Integer> s, int i, boolean[] visited) {
  272.         if (!visited[i]) {
  273.             visited[i] = true;
  274.             Iterator<GraphNode<E>> it = adjList[i].getNeighbors().iterator();
  275.             System.out.println("dfsVisit: " + i + " Stack=" + s);
  276.             while (it.hasNext()) {
  277.                 dfsVisit(s, it.next().getIndex(), visited);
  278.             }
  279.             s.push(i);
  280.             System.out.println("--dfsVisit: " + i + " Stack=" + s);
  281.         }
  282.     }
  283.  
  284.     void topological_sort_dfs() {
  285.         boolean visited[] = new boolean[num_nodes];
  286.         for (int i = 0; i < num_nodes; i++) {
  287.             visited[i] = false;
  288.         }
  289.  
  290.         Stack<Integer> s = new Stack<Integer>();
  291.  
  292.         for (int i = 0; i < num_nodes; i++) {
  293.             dfsVisit(s, i, visited);
  294.         }
  295.         System.out.println("----Stack=" + s);
  296.         while (!s.isEmpty()) {
  297.             System.out.println(adjList[s.pop()]);
  298.         }
  299.     }
  300.  
  301.     /***********************************************************************************************************/
  302.  
  303.     @Override
  304.     public String toString() {
  305.         String ret = new String();
  306.         for (int i = 0; i < this.num_nodes; i++)
  307.             ret += i + ": " + adjList[i] + "\n";
  308.         return ret;
  309.     }
  310.  
  311. }
  312.  
  313. class Cell {
  314.     Integer x;
  315.     Integer y;
  316.     Integer dis;
  317.  
  318.     public Cell(Integer x, Integer y, Integer dis) {
  319.         this.x = x;
  320.         this.y = y;
  321.         this.dis = dis;
  322.     }
  323. }
  324.  
  325. /**
  326.  * Дадена е една шаховска табла mxn и на неа е даден една шаховска фигура - коњ поставен во некое поле (x,y) на таблата. Коњот на шаховската табла легално во еден потег може да се движи или за две позиции вертикално и една хоризонтално или за две позиции хоризонтално и една вертикално, т.е. од позиција (x,y) може да се движи на една од следните позиции (x±1,y±2) или (x±2,y±1) (види слика). Да се најде минималниот број на потези за коњот да се придвижи од едно дадено почетно поле до едно дадено крајно поле на таблата.
  327.  * <p>
  328.  * enter image description here
  329.  * <p>
  330.  * Влез: Во првиот ред од влезот се дадени бројот на редици и колони на таблата (5<=m,n<=100), а во вториот ред се дадени полињата на почетокот и крајот на движењето на коњот (x1,y1) и (x2,y2) .
  331.  * <p>
  332.  * Излез: Да се испечати минималниот број на потези за коњот да се придвижи од едно дадено почетно поле до едно дадено крајно поле на таблата.
  333.  * <p>
  334.  * Делумно решение: Задачата се смета за делумно решена доколку се поминати 4 тест примери.
  335.  * <p>
  336.  * Пример:
  337.  * <p>
  338.  * Влез:
  339.  * <p>
  340.  * 5 5
  341.  * <p>
  342.  * 1 2 4 3
  343.  * <p>
  344.  * Излез:
  345.  * <p>
  346.  * 2
  347.  * <p>
  348.  * За да коњот се придвижи од позиција (1,2) до позиција (4,3) на шаховска табла 5x5 потребни се минимум 2 потега.
  349.  * <p>
  350.  * Име на класа (Јава): Board
  351.  */
Advertisement
Add Comment
Please, Sign In to add comment