All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.semanticweb.elk.reasoner.taxonomy.DepthFirstSearch Maven / Gradle / Ivy

There is a newer version: 0.4.3
Show newest version
/**
 * 
 */
package org.semanticweb.elk.reasoner.taxonomy;
/*
 * #%L
 * ELK Reasoner
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2011 - 2012 Department of Computer Science, University of Oxford
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.semanticweb.elk.owl.interfaces.ElkObject;
import org.semanticweb.elk.reasoner.taxonomy.model.TaxonomyNode;
import org.semanticweb.elk.util.collections.ArraySet;

/**
 * Implementation of the depth-first search
 * 
 * @author Pavel Klinov
 * 
 *         [email protected]
 */
public class DepthFirstSearch {
	// The search direction, up or down the taxonomy
	public enum Direction {
		UP {
			@Override
			public Direction reverse() {
				return DOWN;
			}
		},
		DOWN {
			@Override
			public Direction reverse() {
				return UP;
			}
		};

		public abstract Direction reverse();
	};

	public void run(TaxonomyNode start, Direction dir,
			TaxonomyNodeVisitor visitor) {
		List> path = new ArraySet>();
		Set> pathSet = new HashSet>();

		run(start, dir, visitor, path, pathSet);
	}

	private void run(TaxonomyNode node, Direction dir,
			TaxonomyNodeVisitor visitor, List> path,
			Set> pathSet) {
		visitor.visit(node, path);

		if (pathSet.contains(node)) {
			return;
		}
		
		path.add(node);
		pathSet.add(node);		
		// now go depth-first
		for (TaxonomyNode subNode : getSuccessors(node, dir)) {
			run(subNode, dir, visitor, path, pathSet);
		}
		
		path.remove(path.size() - 1);
		pathSet.remove(node);		
	}

	protected static  Set> getSuccessors(
			TaxonomyNode node, Direction dir) {
		switch (dir) {
		case UP:
			return node.getDirectSuperNodes();
		case DOWN:
			return node.getDirectSubNodes();
		default:
			return Collections.> emptySet();
		}
	}
}