将二维数组转换为具有节点和边的图

问题描述

我的问题是,对于我的 pacman 板创建,我使用的是 1d 数组,但我想对幽灵实施 BFS 算法,据我所知,除非我有一个包含节点和边的图,否则我无法执行该算法。 .. 所以在我的代码中,我试图将一个新创建的二维数组转换为一个哈希映射,并使用一个迭代器作为键(节点),该节点包含“值”,它是板上的特定索引。我希望我走在正确的轨道上,但正在为此苦苦挣扎。

package pacman;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.stream.Collectors;

import org.jgrapht.Graph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.DefaultUndirectedGraph;
import org.jgrapht.graph.SimpleWeightedGraph;

/**
 * This class is used to create a graph from a 2d array
 * 
 * @author Kody Berry
 *
 */
public class GraphCreation {
    private final static short levelData[] = { 19,18,22,17,16,24,20,25,28,19,21,26,28 };

    public static Graph<Integer,DefaultEdge> undirectedGraph = new DefaultUndirectedGraph<Integer,DefaultEdge>(
            DefaultEdge.class);

    public static Graph<Integer,DefaultEdge> createGraph(int[][] s) {
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        int k = 1;
        // Getting an iterator
        Iterator<?> mapIterator = map.entrySet().iterator();

        // Adding values to hash map
        for (int i = 0; i < s.length; i++) {
            for (int j = 0; j < s[i].length; j++) {
                if (s[i][j] == 16) {
                    map.put(k,s[i][j]);
                    k++;
                }
            }
        }

        while (mapIterator.hasNext()) {
            Map.Entry mapElement = (Map.Entry)mapIterator.next();
            int t = (int) mapElement.getKey();
            
            undirectedGraph.addVertex(t);
            
        }
        
        return undirectedGraph;
    }

    /**
     * Method used to convert the 1d array game board to a 2d array board
     * 
     * @param s
     * @return
     */
    public static int[][] oneDtoTwoDConverter(short[] s) {

        int array2d[][] = new int[15][15];


        for(int i=0; i<15;i++)
           for(int j=0;j<15;j++)
               array2d[i][j] = s[(j*15) + i]; 

        return array2d;// Returns new 2d array.
    }
    
    // Test output
    public static void main(String[] args) {
        int[][] s = oneDtoTwoDConverter(levelData);
        System.out.println(createGraph(s));
    }
}

我目前的输出如下。

([],[])

我也在使用 JGraphT 库。我还没有弄清楚如何创建边缘,因此如果您对此有任何建议,我将不胜感激。

附注。如果您对如何执行此操作有更好的想法,请告诉我!谢谢:)

解决方法

可能还有更多问题,但对我来说最明显的是,您在填充地图之前创建了迭代器。当你迭代它时,它会给你填充之前的内容,所以它是空的。

如果您将 audiofile = flask.request.files['file'] filename = werkzeug.utils.secure_filename(audiofile.filename) audiofile.save('Audio/' + filename) 移到循环下方,则应该会发生更多情况。

但是这个对“s[i][j] == 16”的检查对我来说也有点可疑,但这我还没有考虑得足够多,但不知何故我希望你的地图看起来像{1:16,2: 16,3: 16,...} 用python术语来写。