Algorithm KMP/DFS&BFS

一、KMP

public static int[] getNext(String matcher) {
    int next[] = new int[matcher.length()];
    int j = 0,
    k = -1;
    next[0] = -1;
    while (j < matcher.length() - 1) {
        if (k == -1 || matcher.charAt(j) == matcher.charAt(k)) {
            j++;
            k++;
            next[j] = k;

        } else k = next[k];
    }
    return next;
}
public static int kmpIndex(String context, String matcher) {
    int next[] = getNext(matcher);
    int i = 0,
    j = 0;
    while (i < context.length() && j < matcher.length()) {
        if (j == -1 || context.charAt(i) == matcher.charAt(j)) {
            i++;
            j++;
        } else j = next[j]; //j后退
    }
    if (j >= matcher.length()) return (i - matcher.length()); //返回首字母下标
    return - 1; //没找到
}

 

二、BFS&DFS

class Edge{
    int v;//指向的顶点
    int len;//边的长度
    Edge next;
}
class Vertex{
    int v;//顶点信息
    //List<Edge> edgeList = new ArrayList<Edge>();//边集
    Edge firstEdge;//首条边;
}
class Graph{
    int vertexs;
    int edges;
    List<Vertex> vertexList = new ArrayList<Vertex>(); //顶点集
}
public class DFSBFS {

    /**
     * @param g 整个图
     * @param index 初始顶点所在的index下标
     */
    public static void DFS(Graph g, int index,boolean visited[]){
        visited[index] = true;
        System.out.println(" visit :" + index);
        Vertex init = g.vertexList.get(index);
        Edge edge = init.firstEdge;
        while(edge != null){
            if(!visited[edge.v])
                DFS(g,edge.v,visited);
            edge = edge.next;
        }
    }
    /**
     * @param g 整个图
     * @param index 初始顶点所在的index下标
     */
    public static void BFS(Graph g, int index){
        int capacity = g.vertexList.size();
        boolean visited[] = new boolean[capacity]; 
        Queue<Integer> queue = new ArrayBlockingQueue<Integer>(capacity);
        System.out.println(" visit :" + index);
        queue.add(index);
        while( !queue.isEmpty()){
            int top = queue.poll();
            Edge edge = g.vertexList.get(top).firstEdge;
            while( edge!= null){
                int curIndex = edge.v;
                if( !visited[curIndex]){
                    System.out.println(" visit :" + curIndex);
                    visited[curIndex] = true;
                    queue.add(curIndex);
                }
                edge = edge.next;
            }
        }
    }
    
    public static void main(String[] args) {
        Graph g = new Graph();
        boolean visited[] = new boolean[g.vertexList.size()]; 
        DFS(g,0,visited);
    }
    
    
}
 

 

三、

四、

 

posted @ 2016-01-03 15:01  √珞珈搬砖工√  阅读(82)  评论(0)    收藏  举报