使用Java中的ArrayList实现Bfs

时间:2016-03-18 12:28:43

标签: java arraylist queue breadth-first-search

我已经使用java编写了bfs实现的代码,我想要帮助优化这段代码:

 package graphs;

 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.PrintWriter;
 import static java.lang.System.out;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.Queue;
 import java.util.StringTokenizer;


 public class Bfs {

static ArrayList<ArrayList<Integer>> a;
static boolean visited[];
static Queue q=new LinkedList<Integer>();
public static void main(String args[]) throws IOException
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    PrintWriter w = new PrintWriter(System.out);
    out.println("Enter the vertice and edge");
    StringTokenizer st=new StringTokenizer(br.readLine());
    int vertice,edge;

    vertice=ip(st.nextToken());
    edge=ip(st.nextToken());
    a=new ArrayList<ArrayList<Integer>>(vertice);
    for(int i=0;i<vertice;i++)
    {
        a.add(new ArrayList<Integer>());
    }
    out.println("Enter all the points X Y");
    int n=vertice;
    while(n-->0)
    {
        st=new StringTokenizer(br.readLine());
        graph(ip(st.nextToken()),ip(st.nextToken()));

    }
    visited=new boolean[vertice];
    out.println("Enter any vertice number");
    bfs(ip(br.readLine()));

   // w.println(a);
    w.close();
}

public static void graph(int p1,int p2)
{
    a.get(p1).add(p2);
    a.get(p2).add(p1);
}

public static void bfs(int vertice)
{
    if(!visited[vertice])
    {
        visited[vertice]=true;
        q.add(vertice);
    }
    Iterator it=a.get(vertice).iterator();

    while(it.hasNext())
    {
        int currver=(int)it.next();
      // System.out.println(visited[currver]+" :"+currver);

        if(!visited[currver])
        {
            q.add(currver);
            visited[currver]=true;
        }
    }
//   System.out.println(q); 
    System.out.println(q.poll());
    if(!q.isEmpty())
    {
        bfs((int)q.peek());
    }
}
   public static int ip(String s){
    return Integer.parseInt(s);
}
}

实际上我正在使用递归调用bfs并想删除它,所以如果你可以删除那个递归调用它将是一个帮助。

2 个答案:

答案 0 :(得分:1)

ImageView icon = ImageCache.getImage("refresh.png");
RotateTransition rotateTransition = new RotateTransition(Duration.millis(2000), icon);
rotateTransition.setByAngle(360.0);
rotateTransition.setCycleCount(Timeline.INDEFINITE);

rotateTransition.play();

这里推送的是一个布尔数组,它基本上跟踪顶点是否已被推送到队列。还记得用其中一个顶点初始化队列。我认为在这种情况下你可以消除递归。

答案 1 :(得分:0)

谢谢@ user98274 我用bfs()方法进行了一些更改(我认为复杂性是相同的),代码看起来像

WARN  [com.arjuna.ats.jta] (Periodic Recovery) ARJUNA016037: Could not find new XAResource to use for recovering non-serializable XAResource XAResourceRecord < resource:null, txid:< formatId=131077, gtrid_length=29, bqual_length=36, tx_uid=0:ffff84ba6b0e:45f1fb89:56ea3bdb:4c, node_name=1, branch_uid=0:ffff84ba6b0e:45f1fb89:56ea3bdb:4d, subordinatenodename=null, eis_name=unknown eis name >, heuristic: TwoPhaseOutcome.FINISH_OK com.arjuna.ats.internal.jta.resources.arjunacore.XAResourceRecord@48a649 >

WARN  [com.arjuna.ats.jta] (Periodic Recovery) ARJUNA016038: No XAResource to recover < formatId=131077, gtrid_length=29, bqual_length=36, tx_uid=0:ffff84ba6b0e:45f1fb89:56ea3bdb:4c, node_name=1,

branch_uid=0:ffff84ba6b0e:45f1fb89:56ea3bdb:4d, subordinatenodename=null, eis_name=unknown eis name >


ERROR [io.undertow.request] (default I/O-1) UT005001: An exception occurred processing the request: java.lang.IllegalStateException: Wrong magic number

    at io.undertow.server.protocol.ajp.AjpRequestParser.parse(AjpRequestParser.java:185)

    at io.undertow.server.protocol.ajp.AjpReadListener.handleEvent(AjpReadListener.java:160)

    at io.undertow.server.protocol.ajp.AjpOpenListener.handleEvent(AjpOpenListener.java:117)

    at io.undertow.server.protocol.ajp.AjpOpenListener.handleEvent(AjpOpenListener.java:44)

    at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92) [xnio-api-3.3.0.Final.jar:3.3.0.Final]

    at org.xnio.ChannelListeners$10.handleEvent(ChannelListeners.java:291) [xnio-api-3.3.0.Final.jar:3.3.0.Final]

    at org.xnio.ChannelListeners$10.handleEvent(ChannelListeners.java:286) [xnio-api-3.3.0.Final.jar:3.3.0.Final]

    at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92) [xnio-api-3.3.0.Final.jar:3.3.0.Final]

    at org.xnio.nio.NioTcpServerHandle.handleReady(NioTcpServerHandle.java:53) [xnio-nio-3.3.0.Final.jar:3.3.0.Final]

    at org.xnio.nio.WorkerThread.run(WorkerThread.java:539) [xnio-nio-3.3.0.Final.jar:3.3.0.Final]

同样在main()方法中,我添加了 public static void bfs(){ while(!q.isEmpty()){ int v = (int)q.poll(); System.out.println(v); visited[v]=true; Iterator it = a.get(v).iterator(); while(it.hasNext()){ int vert = (int)it.next(); if(!visited[vert]){ q.add(vert); visited[vert]=true; } } } } ,我想要bfs。