Filip_Markoski

[ADSx] - Board (Simple)

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