Filip_Markoski

[ADSx] - Board (Slow)

Jan 17th, 2018
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 19.12 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. class Cell {
  4.     Integer x;
  5.     Integer y;
  6.     Integer dis;
  7.  
  8.     public Cell(Integer x, Integer y, Integer dis) {
  9.         this.x = x;
  10.         this.y = y;
  11.         this.dis = dis;
  12.     }
  13. }
  14.  
  15. public class Board {
  16.  
  17.     public static <T> void printMatrix(T matrix[][]) {
  18.         System.out.println("Main.");
  19.         Arrays.stream(matrix)
  20.                 .map(Arrays::toString)
  21.                 .forEach(System.out::println);
  22.     }
  23.  
  24.     public static boolean isInside(int x, int y, int N) {
  25.         if (x >= 1 && x <= N && y >= 1 && y <= N) return true;
  26.         return false;
  27.     }
  28.  
  29.     public static int minStepToReachTarget(int knightPos[], int targetPos[], int N) {
  30.         //  x and y direction, where a knight can move
  31.         int dx[] = {-2, -1, 1, 2, -2, -1, 1, 2};
  32.         int dy[] = {-1, -2, -2, -1, 1, 2, 2, 1};
  33.  
  34.         //  queue for storing states of knight in board
  35.         Queue<Cell> queue = new ArrayDeque<>();
  36.  
  37.         //  push starting position of knight with 0 distance
  38.         queue.add(new Cell(knightPos[0], knightPos[1], 0));
  39.  
  40.         Cell t;
  41.         int x, y;
  42.         boolean visited[][] = new boolean[N + 1][N + 1];
  43.  
  44.         //  make all cell unvisited
  45.         for (int i = 1; i <= N; i++)
  46.             for (int j = 1; j <= N; j++)
  47.                 visited[i][j] = false;
  48.  
  49.         //  visit starting state
  50.         visited[knightPos[0]][knightPos[1]] = true;
  51.  
  52.         //  loop until we have one element in queue
  53.         while (!queue.isEmpty()) {
  54.             t = queue.poll();
  55.             visited[t.x][t.y] = true;
  56.  
  57.             // if current cell is equal to target cell,
  58.             // return its distance
  59.             if (t.x == targetPos[0] && t.y == targetPos[1])
  60.                 return t.dis;
  61.  
  62.  
  63.             //  loop for all reahable states
  64.             for (int i = 0; i < dx.length; i++) {
  65.                 x = t.x + dx[i];
  66.                 y = t.y + dy[i];
  67.  
  68.                 // If rechable state is not yet visited and
  69.                 // inside board, push that state into queue
  70.                 if (isInside(x, y, N) && !visited[x][y])
  71.                     queue.add(new Cell(x, y, t.dis + 1));
  72.  
  73.             }
  74.         }
  75.         return -1;
  76.     }
  77.  
  78.     public static void main(String args[]) {
  79.         String text = "100 100\n" +
  80.                 "2 100 50 50";
  81.         Scanner scanner = new Scanner(text);
  82.         //Scanner scanner = new Scanner(System.in);
  83.         int rows = scanner.nextInt();
  84.         int columns = scanner.nextInt();
  85.         scanner.nextLine();
  86.         int x1 = scanner.nextInt();
  87.         int y1 = scanner.nextInt();
  88.         int x2 = scanner.nextInt();
  89.         int y2 = scanner.nextInt();
  90.  
  91.         int knightPos[] = {x1, y1};
  92.         int targetPos[] = {x2, y2};
  93.        
  94.         /**
  95.          * https://en.wikipedia.org/wiki/Knight%27s_graph
  96.          * https://www.geeksforgeeks.org/minimum-steps-reach-target-knight/
  97.          * */
  98.        
  99.         int minStepToReachTarget = minStepToReachTarget(knightPos, targetPos, rows);
  100.         System.out.println(minStepToReachTarget);
  101.  
  102.         /**
  103.          * I think a faster solution can be attained by using dijkstra's
  104.          * but I don't know how to represent the nodes
  105.          * */
  106.  
  107.         Graph<Integer> graph = new Graph<>(rows);
  108.         int dx[] = {-2, -1, 1, 2, -2, -1, 1, 2};
  109.         int dy[] = {-1, -2, -2, -1, 1, 2, 2, 1};
  110.         for (int i = 0; i < rows * rows; i++) {
  111.             for (int j = 0; j < dx.length; j++) {
  112.                 //graph.addEdge(i, i + dx[i]);
  113.             }
  114.         }
  115.  
  116.     }
  117. }
  118.  
  119. class GraphNode<E> {
  120.     private int index; //index (reden broj) na temeto vo grafot
  121.     private E info;
  122.     private LinkedList<GraphNodeNeighbor<E>> neighbors;
  123.  
  124.     public GraphNode(int index, E info) {
  125.         this.index = index;
  126.         this.info = info;
  127.         neighbors = new LinkedList<GraphNodeNeighbor<E>>();
  128.     }
  129.  
  130.     public boolean containsNeighbor(GraphNode<E> o) {
  131.         GraphNodeNeighbor<E> pom = new GraphNodeNeighbor<E>(o, 0);
  132.         return neighbors.contains(pom);
  133.     }
  134.  
  135.     public void addNeighbor(GraphNode<E> o, float weight) {
  136.         GraphNodeNeighbor<E> pom = new GraphNodeNeighbor<E>(o, weight);
  137.         neighbors.add(pom);
  138.     }
  139.  
  140.     public void removeNeighbor(GraphNode<E> o) {
  141.         GraphNodeNeighbor<E> pom = new GraphNodeNeighbor<E>(o, 0);
  142.         if (neighbors.contains(pom))
  143.             neighbors.remove(pom);
  144.     }
  145.  
  146.     @Override
  147.     public String toString() {
  148.         String ret = "INFO:" + info + " SOSEDI:";
  149.         for (int i = 0; i < neighbors.size(); i++)
  150.             ret += "(" + neighbors.get(i).node.info + "," + neighbors.get(i).weight + ") ";
  151.         return ret;
  152.  
  153.     }
  154.  
  155.     public void updateNeighborWeight(GraphNode<E> o, float weight) {
  156.         Iterator<GraphNodeNeighbor<E>> i = neighbors.iterator();
  157.         while (i.hasNext()) {
  158.             GraphNodeNeighbor<E> pom = i.next();
  159.             if (pom.node.equals(o))
  160.                 pom.weight = weight;
  161.         }
  162.  
  163.     }
  164.  
  165.     @Override
  166.     public boolean equals(Object obj) {
  167.         @SuppressWarnings("unchecked")
  168.         GraphNode<E> pom = (GraphNode<E>) obj;
  169.         return (pom.info.equals(this.info));
  170.     }
  171.  
  172.     public int getIndex() {
  173.         return index;
  174.     }
  175.  
  176.     public void setIndex(int index) {
  177.         this.index = index;
  178.     }
  179.  
  180.     public E getInfo() {
  181.         return info;
  182.     }
  183.  
  184.     public void setInfo(E info) {
  185.         this.info = info;
  186.     }
  187.  
  188.     public LinkedList<GraphNodeNeighbor<E>> getNeighbors() {
  189.         return neighbors;
  190.     }
  191.  
  192.     public void setNeighbors(LinkedList<GraphNodeNeighbor<E>> neighbors) {
  193.         this.neighbors = neighbors;
  194.     }
  195.  
  196.  
  197. }
  198.  
  199. class GraphNodeNeighbor<E> {
  200.     GraphNode<E> node;
  201.     float weight;
  202.  
  203.     public GraphNodeNeighbor(GraphNode<E> node, float weight) {
  204.         this.node = node;
  205.         this.weight = weight;
  206.     }
  207.  
  208.     public GraphNodeNeighbor(GraphNode<E> node) {
  209.         this.node = node;
  210.         this.weight = 0;
  211.     }
  212.  
  213.     @Override
  214.     public boolean equals(Object obj) {
  215.         @SuppressWarnings("unchecked")
  216.         GraphNodeNeighbor<E> pom = (GraphNodeNeighbor<E>) obj;
  217.         return pom.node.equals(this.node);
  218.     }
  219. }
  220.  
  221. class Graph<E> {
  222.  
  223.     int num_nodes;
  224.     GraphNode<E> adjList[];
  225.  
  226.     @SuppressWarnings("unchecked")
  227.     public Graph(int num_nodes, E[] list) {
  228.         this.num_nodes = num_nodes;
  229.         adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
  230.         for (int i = 0; i < num_nodes; i++)
  231.             adjList[i] = new GraphNode<E>(i, list[i]);
  232.     }
  233.  
  234.     @SuppressWarnings("unchecked")
  235.     public Graph(int num_nodes) {
  236.         this.num_nodes = num_nodes;
  237.         adjList = (GraphNode<E>[]) new GraphNode[num_nodes];
  238.         for (int i = 0; i < num_nodes; i++)
  239.             adjList[i] = new GraphNode<E>(i, null);
  240.     }
  241.  
  242.     int adjacent(int x, int y) {
  243.         // proveruva dali ima vrska od jazelot so
  244.         // indeks x do jazelot so indeks y
  245.         return (adjList[x].containsNeighbor(adjList[y])) ? 1 : 0;
  246.     }
  247.  
  248.     void addEdge(int x, int y, float tezina) {
  249.         // dodava vrska od jazelot so indeks x do jazelot so indeks y so tezina
  250.         // i obratno
  251.         if (adjList[x].containsNeighbor(adjList[y])) {
  252.             adjList[x].updateNeighborWeight(adjList[y], tezina);
  253.             adjList[y].updateNeighborWeight(adjList[x], tezina);
  254.         } else {
  255.             adjList[x].addNeighbor(adjList[y], tezina);
  256.             adjList[y].addNeighbor(adjList[x], tezina);
  257.         }
  258.     }
  259.  
  260.     void deleteEdge(int x, int y) {
  261.         adjList[x].removeNeighbor(adjList[y]);
  262.         adjList[y].removeNeighbor(adjList[x]);
  263.     }
  264.  
  265.     /*************************** KRUSKAL ***********************************************************************/
  266.  
  267.     // Metoda koja generira niza od site rebra vo grafot
  268.     public Edge[] getAllEdges() {
  269.         int totalEdges = 0;
  270.         for (int i = 0; i < this.num_nodes; i++) {
  271.             // za sekoe teme go dodavame brojot na sosedi koi gi ima
  272.             totalEdges += this.adjList[i].getNeighbors().size();
  273.         }
  274.  
  275.         totalEdges /= 2; //bidejki e nenasocen graf, sekoe rebro se javuva kaj dve teminja
  276.  
  277.         Edge[] edges = new Edge[totalEdges];
  278.         int index = 0;
  279.         for (int i = 0; i < this.num_nodes; i++) {
  280.             for (int j = 0; j < this.adjList[i].getNeighbors().size(); j++) {
  281.                 int index1 = this.adjList[i].getIndex();
  282.                 // se zemaat indeksot i tezinata na j-ot sosed na temeto i
  283.                 int index2 = this.adjList[i].getNeighbors().get(j).node
  284.                         .getIndex();
  285.                 float weight = this.adjList[i].getNeighbors().get(j).weight;
  286.                 if (index2 > index1) //bidejki grafot e nenasocen, da ne go zemame sekoe rebro dva pati
  287.                     edges[index++] = new Edge(index1, index2, weight);
  288.             }
  289.         }
  290.  
  291.         return edges;
  292.     }
  293.  
  294.     // Metoda koja gi sortira site rebra
  295.     private void sortEdges(Edge[] edges) {
  296.         for (int i = 0; i < edges.length - 1; i++) {
  297.             for (int j = i + 1; j < edges.length; j++) {
  298.                 if (edges[i].getWeight() > edges[j].getWeight()) {
  299.                     Edge tmp = edges[i];
  300.                     edges[i] = edges[j];
  301.                     edges[j] = tmp;
  302.                 }
  303.             }
  304.         }
  305.  
  306.     }
  307.  
  308.     //Metoda koja pravi unija na dve drva
  309.     private void union(int u, int v, int[] vrski) {
  310.         int findWhat, replaceWith;
  311.  
  312.         if (u < v) {
  313.             findWhat = vrski[v];
  314.             replaceWith = vrski[u];
  315.         } else {
  316.             findWhat = vrski[u];
  317.             replaceWith = vrski[v];
  318.         }
  319.  
  320.         //za dvete poddrva stava ist index
  321.         //vo vrski t.e. gi spojuva
  322.         for (int i = 0; i < vrski.length; i++) {
  323.             if (vrski[i] == findWhat) {
  324.                 vrski[i] = replaceWith;
  325.             }
  326.         }
  327.     }
  328.  
  329.     List<Edge> kruskal() {
  330.         /*
  331.          * Pomoshna niza za sledenje na kreiranite drva
  332.          * Ako dve teminja se del od isto poddrvo
  333.          * togash imaat ista vrednost vo nizata
  334.          */
  335.         int vrski[] = new int[this.num_nodes];
  336.  
  337.         // niza koja gi sodrzi site rebra
  338.         Edge[] edges = this.getAllEdges();
  339.         // se sortiraat rebrata spored tezinite vo neopagjacki redosled
  340.         this.sortEdges(edges);
  341.  
  342.         // inicijalizacija na pomosnata niza za evidencija,
  343.         // sekoj jazel si e posebno drvo
  344.         for (int i = 0; i < this.num_nodes; i++)
  345.             vrski[i] = i;
  346.  
  347.         // lista koja kje gi sodrzi MST rebra
  348.         List<Edge> mstEdges = new ArrayList<Edge>();
  349.  
  350.         for (int i = 0; i < edges.length; i++) {
  351.             //za sekoe rebro vo sortiran redosled
  352.             Edge e = edges[i];
  353.  
  354.             if (vrski[e.getFrom()] != vrski[e.getTo()]) {
  355.                 //ako teminjata na ova rebro ne se vo isto poddrvo
  356.                 //ova rebro e MST rebro
  357.                 mstEdges.add(e);
  358.                 //sega dvete teminja treba da se vo isto poddrvo
  359.                 //t.e se pravi merge (unija) t.s. vo nizata vrski
  360.                 //za site elementi od dvete poddrva
  361.                 //go setira istiot (najmal) element od dvete poddrva
  362.                 //vrski = this.union(e.getFrom(), e.getTo(), vrski);
  363.                 this.union(e.getFrom(), e.getTo(), vrski);
  364.             }
  365.  
  366.             //ako sme dodale num_nodes-1 rebra moze da prestaneme
  367.             if (mstEdges.size() == (this.num_nodes - 1))
  368.                 break;
  369.         }
  370.  
  371.         return mstEdges;
  372.     }
  373.  
  374.     /*******************************************************************************************************/
  375.     /************************ PRIM **************************************************************************/
  376.  
  377.     //Metoda koja go naogja najmaloto rebro do
  378.     //teme na neposeten sosed
  379.     private Edge getMinimalEdge(boolean[] included) {
  380.         int index1 = Integer.MAX_VALUE, index2 = Integer.MAX_VALUE;
  381.         float minweight = Float.MAX_VALUE;
  382.  
  383.         for (int i = 0; i < this.num_nodes; i++) {
  384.             if (included[i]) {
  385.                 //ako e vkluceno temeto i
  386.                 //izmini gi negovite nevkluceni sosedi
  387.                 Iterator<GraphNodeNeighbor<E>> it = adjList[i].getNeighbors().iterator();
  388.                 while (it.hasNext()) {
  389.                     GraphNodeNeighbor<E> pom = it.next();
  390.                     //ako sosedot ne e poseten i ima do sega najmala tezina
  391.                     if (!included[pom.node.getIndex()] && pom.weight < minweight) {
  392.                         index1 = i;
  393.                         index2 = pom.node.getIndex();
  394.                         minweight = pom.weight;
  395.                     }
  396.                 }
  397.             }
  398.         }
  399.  
  400.         if (minweight < Float.MAX_VALUE) {
  401.             Edge ret = new Edge(index1, index2, minweight);
  402.             return ret;
  403.         }
  404.         return null;
  405.     }
  406.  
  407.  
  408.     List<Edge> prim(int start_index) {
  409.         // lista koja kje gi sodrzi MST rebra
  410.         List<Edge> mstEdges = new ArrayList<Edge>();
  411.  
  412.         boolean included[] = new boolean[this.num_nodes];
  413.         for (int i = 0; i < this.num_nodes; i++)
  414.             included[i] = false;
  415.  
  416.         included[start_index] = true;
  417.  
  418.         for (int i = 0; i < this.num_nodes - 1; i++) {
  419.             Edge e = this.getMinimalEdge(included);
  420.             if (e == null) {
  421.                 System.out.println("Ne mozat da se povrzat site jazli");
  422.                 break;
  423.             }
  424.             included[e.getFrom()] = included[e.getTo()] = true;
  425.             mstEdges.add(e);
  426.         }
  427.  
  428.         return mstEdges;
  429.     }
  430.  
  431.     /*******************************************************************************************************/
  432.     /***************** DIJKSTRA ******************************************************************************/
  433.  
  434.     float[] dijkstra(int from) {
  435.  
  436.         /* Minimalna cena do sekoe od teminjata */
  437.         float distance[] = new float[this.num_nodes];
  438.         /* dali za temeto e najdena konecnata (minimalna) cena */
  439.         boolean finalno[] = new boolean[this.num_nodes];
  440.         for (int i = 0; i < this.num_nodes; i++) {
  441.             distance[i] = -1;
  442.             finalno[i] = false;
  443.         }
  444.  
  445.         finalno[from] = true;
  446.         distance[from] = 0;
  447.  
  448.         /*
  449.          * vo sekoj cekor za edno teme se dobiva konecna minimalna cena
  450.          */
  451.         for (int i = 1; i < this.num_nodes; i++) {
  452.             /* za site sledbenici na from presmetaj ja cenata */
  453.             Iterator<GraphNodeNeighbor<E>> it = adjList[from].getNeighbors().iterator();
  454.             while (it.hasNext()) {
  455.                 GraphNodeNeighbor<E> pom = it.next();
  456.                 /* ako grankata kon sosedot nema konecna cena */
  457.                 if (!finalno[pom.node.getIndex()]) {
  458.                     /* ako ne e presmetana cena za temeto */
  459.                     if (distance[pom.node.getIndex()] <= 0) {
  460.                         distance[pom.node.getIndex()] = distance[from]
  461.                                 + pom.weight;
  462.                     }
  463.                     /* inaku, ako e pronajdena poniska */
  464.                     else if (distance[from] + pom.weight < distance[pom.node
  465.                             .getIndex()]) {
  466.                         distance[pom.node.getIndex()] = distance[from]
  467.                                 + pom.weight;
  468.                     }
  469.                 }
  470.             }
  471.  
  472.             /* najdi teme so min. cena koja ne e konecna */
  473.             boolean minit = false; /* min. ne e inicijaliziran */
  474.             int k = -1;
  475.             float minc = -1;
  476.             /* proveri gi site teminja */
  477.             for (int j = 0; j < this.num_nodes; j++) {
  478.                 if (!finalno[j] && distance[j] != -1) { /*ako cenata ne e  konecna*/
  479.                     if (!minit) { /* ako ne e inicijaliziran minimumot */
  480.                         minc = distance[k = j]; /* proglasi go ova e minimum */
  481.                         minit = true; /* oznaci deka min e inicijaliziran */
  482.                     }
  483.                     /* proveri dali e pronajdeno teme so pomala cena */
  484.                     else if (minc > distance[j] && distance[j] > 0)
  485.                         minc = distance[k = j];
  486.                 }
  487.             }
  488.             finalno[from = k] = true;
  489.         }
  490.  
  491.         return distance;
  492.  
  493.     }
  494.  
  495.     /*******************************************************************************************************/
  496.  
  497.     @Override
  498.     public String toString() {
  499.         String ret = new String();
  500.         for (int i = 0; i < this.num_nodes; i++)
  501.             ret += adjList[i] + "\n";
  502.         return ret;
  503.     }
  504.  
  505. }
  506.  
  507. class Edge {
  508.     private int fromVertex, toVertex;
  509.     private float weight;
  510.  
  511.     public Edge(int from, int to, float weight) {
  512.         this.fromVertex = from;
  513.         this.toVertex = to;
  514.         this.weight = weight;
  515.     }
  516.  
  517.     public int getFrom() {
  518.         return this.fromVertex;
  519.     }
  520.  
  521.     public int getTo() {
  522.         return this.toVertex;
  523.     }
  524.  
  525.     public float getWeight() {
  526.         return this.weight;
  527.     }
  528.  
  529.     @Override
  530.     public String toString() {
  531.         return "(" + fromVertex + "," + toVertex + ")=" + weight + " ";
  532.     }
  533.  
  534.  
  535. }
  536.  
  537. /**
  538.  * Дадена е една шаховска табла mxn и на неа е даден една шаховска фигура - коњ поставен во некое поле (x,y) на таблата. Коњот на шаховската табла легално во еден потег може да се движи или за две позиции вертикално и една хоризонтално или за две позиции хоризонтално и една вертикално, т.е. од позиција (x,y) може да се движи на една од следните позиции (x±1,y±2) или (x±2,y±1) (види слика). Да се најде минималниот број на потези за коњот да се придвижи од едно дадено почетно поле до едно дадено крајно поле на таблата.
  539.  * <p>
  540.  * enter image description here
  541.  * <p>
  542.  * Влез: Во првиот ред од влезот се дадени бројот на редици и колони на таблата (5<=m,n<=100), а во вториот ред се дадени полињата на почетокот и крајот на движењето на коњот (x1,y1) и (x2,y2) .
  543.  * <p>
  544.  * Излез: Да се испечати минималниот број на потези за коњот да се придвижи од едно дадено почетно поле до едно дадено крајно поле на таблата.
  545.  * <p>
  546.  * Делумно решение: Задачата се смета за делумно решена доколку се поминати 4 тест примери.
  547.  * <p>
  548.  * Пример:
  549.  * <p>
  550.  * Влез:
  551.  * <p>
  552.  * 5 5
  553.  * <p>
  554.  * 1 2 4 3
  555.  * <p>
  556.  * Излез:
  557.  * <p>
  558.  * 2
  559.  * <p>
  560.  * За да коњот се придвижи од позиција (1,2) до позиција (4,3) на шаховска табла 5x5 потребни се минимум 2 потега.
  561.  * <p>
  562.  * Име на класа (Јава): Board
  563.  */
Advertisement
Add Comment
Please, Sign In to add comment