搜索矩阵并返回值的坐标

时间:2015-03-22 21:15:09

标签: java matrix

我需要在矩阵中搜索某个值并返回其坐标;我已经制作了以下脚本/函数。但是,该函数不起作用,因为显然当findIndexWithValue中的if语句运行时,它会查找不在数组中的坐标(为高)。任何人都可以帮助我,或者提供一种更有效的方法来做我想做的事情吗?

package main;

public class SolveMaze {

Pos start = new Pos(0,0);
Pos end = new Pos(0,0);

public static int getMazeWidth(int[][] maze){
    if (maze == null){
        System.out.println("Entered Maze Has Returned Null For Width");
        return 0;
    } else {
    return maze.length;

    }
}

public static int getMazeHeight(int[][] maze){
    if (maze == null){
        System.out.println("Entered Maze Has Returned Null For Height");
        return 0;
    } else {
    return maze[0].length;
    }
}




public static Pos findIndexWithValue(int[][] maze, int value){

    if (maze == null){
        System.out.println("Maze is NULL! (FindIndexWithValue)");
        return null;
    } else {
        for (int i1 = 0; i1 < getMazeWidth(maze) - 1; i1++){ //1
        int cordX = 0;
        int cordY = 0;
        cordY = 0;

            for (int i2 = 0; i2 < getMazeHeight(maze) - 1; i2++){ //9
                if (maze[cordX][cordY] == value){
                    Pos returnPos = new Pos(cordX, cordY);
                    return returnPos;
                }
                cordY++;
            }
            cordX++;

        }
    }
    System.out.println("The Value You Are Looking For is not Present (findIndexWithValue)");
    return null;
}


}

主要类是:

package main;

public class MazeSolver {

final static int[][] maze = {
    {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
    {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
    {-1, 1,-1,-1,-1,-1,-1,-1,-1,-1},
    {-1, 0,-1,-1,-1,-1,-1,-1,-1,-1},
    {-1, 0,-1,-1,-1,-1,-1,-1,-1,-1},
    {-1, 0,-1,-1,-1,-1,-1,-1,-1,-1},
    {-1, 0,-1,-1,-1,-1,-1,-1,-1,-1},
    {-1, 0,-1,-1,-1,-1,-1,-1,-1,-1},
    {-1, 0, 0, 0, 0, 0, 0, 0, 1,-1},
    {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
    };

public static void main(String args[]){

Pos test = new Pos(0,0);
test = SolveMaze.findIndexWithValue(maze, 1);
System.out.println(test.getX() + " " + test.getY());


}

}

1 个答案:

答案 0 :(得分:0)

你在for for for循环中做了一些奇怪的事情: - )

这应该解决它:

public static Pos findIndexWithValue(int[][] maze, int value) {

    if (maze == null) {
        System.out.println("Maze is NULL! (FindIndexWithValue)");
        return null;
    } else {
        for (int x = 0; x < getMazeWidth(maze); x++) {
            for (int y = 0; y < getMazeHeight(maze); y++) {
                if (maze[x][y] == value) {
                    Pos returnPos = new Pos(x, y);
                    return returnPos;
                }
            }
        }
    }
    System.out.println("The Value You Are Looking For is not Present (findIndexWithValue)");
    return null;
}

此外,只是一个提示:永远不要命名您的变量i1或i2。无论谁阅读你的代码,都很难理解它。