Problemas com Martrizes

5 respostas
Nivekzin

Estou tentando fazer um labirinto numa matriz… sendo que está começando a dar este erro com estouro de Array :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
	at br.com.Lab.Maze.nextPosition(Maze.java:72)
	at br.com.Lab.Maze.walk(Maze.java:49)
	at br.com.Lab.Maze.walk(Maze.java:43)
	at br.com.Lab.Maze.walk(Maze.java:43)
	at br.com.Lab.Maze.walk(Maze.java:46)
	at br.com.Lab.Maze.walk(Maze.java:52)
	at br.com.Lab.Maze.walk(Maze.java:52)
	at br.com.Lab.Maze.main(Maze.java:117)

Vou postar o código abaixo para que possam me dar algumas idéias :

package br.com.Lab;

public class Maze {
	
	private static String maze[][] = {
				{ "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1",
						"1", "1", "1", "1" },
				{ "1", "0", "1", "0", "0", "0", "1", "1", "0", "0", "0", "1", "1",
						"1", "1", "1", "1" },
				{ "1", "1", "0", "0", "0", "1", "1", "0", "1", "1", "1", "0", "0",
						"1", "1", "1", "1" },
				{ "1", "0", "1", "1", "0", "0", "0", "0", "1", "1", "1", "1", "0",
						"0", "1", "1", "1" },
				{ "1", "1", "1", "0", "1", "1", "1", "1", "0", "1", "1", "0", "1",
						"1", "0", "0", "1" },
				{ "1", "1", "1", "0", "1", "0", "0", "1", "0", "1", "1", "1", "1",
						"1", "1", "1", "1" },
				{ "1", "0", "0", "1", "1", "0", "1", "1", "0", "1", "1", "1", "1",
						"1", "0", "1", "1" },
				{ "1", "0", "1", "1", "1", "1", "0", "0", "1", "1", "1", "1", "1",
						"1", "1", "1", "1" },
				{ "1", "0", "0", "1", "1", "0", "1", "1", "0", "1", "1", "1", "1",
						"1", "0", "1", "1" },
				{ "1", "1", "1", "0", "0", "0", "1", "1", "0", "1", "1", "0", "0",
						"0", "0", "0", "1" },
				{ "1", "0", "0", "1", "1", "1", "1", "1", "0", "0", "0", "1", "1",
						"1", "1", "0", "1" },
				{ "1", "0", "1", "0", "0", "1", "1", "1", "1", "1", "0", "1", "1",
						"1", "1", "0", "1" },
				{ "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1",
						"1", "1", "1", "1" } };
	
	private static String mark[][];
	
	private static int wall = 1;
	private static int walking;
	
	public static int walk(int x, int y, String direc){
		
		maze[x][y] = "1";
		
		if(direc.equals("N"))
			return walk(x - 1, y, nextPosition(x,y));
		
		else if(direc.equals("NE"))
			return walk(x - 1, y + 1, nextPosition(x,y));
		
		else if(direc.equals("E"))
			return walk(x , y + 1, nextPosition(x,y));
		
		else if(direc.equals("SE"))
			return walk(x + 1, y + 1, nextPosition(x,y));
		
		else if(direc.equals("S"))
			return walk(x + 1, y, nextPosition(x,y));
		
		else if(direc.equals("SW"))
			return walk(x + 1, y - 1, nextPosition(x,y));
		
		else if(direc.equals("W"))
			return walk(x, y - 1, nextPosition(x,y));
		
		else if(direc.equals("NW"))
			return walk(x - 1, y - 1, nextPosition(x,y));
		
		else
			return wall;
	}
	
	public static String nextPosition(int x, int y){
		
		if(maze[x - 1][y].equals("0"))
			return "N";
		
		else if(maze[x - 1][y + 1].equals("0"))
			return "NE";
		
		else if(maze[x][y + 1].equals("0"))
			return "E";
		
		else if(maze[x + 1][y + 1].equals("0"))
			return "SE";
		
		else if(maze[x + 1][y].equals("0"))
			return "S";
		
		else if(maze[x + 1][y - 1].equals("0"))
			return "SW";
			
		else if(maze[x][y -1].equals("0"))
			return "W";
				
		else if(maze[x - 1][y - 1].equals("0"))
			return "NW";
		
		else
			return "X";
	}
	
	private static void exibeMatriz(String[][] matriz){
		for(int i = 0; i < matriz.length; i++){
			for(int j = 0; j < matriz[i].length; j++){
				System.out.print("" + matriz[i][j]);
			}
			System.out.println();
		}
	}
	
	public static void main(String[] args) {
		
		exibeMatriz(maze);
		
		while(walking != 1){
			for(int i = 1; i < maze.length; i++){
				for(int j = 1; j < maze[i].length; j++){
					
					walking = walk(i, j, nextPosition(i, j));
					mark[i][j] = maze[i][j];
				}
				System.out.println("");
			}
		}
		System.out.println("");
		exibeMatriz(mark);
		
	}
	

}

Obs.: É um trabalho sobre recursividade no qual meu professor passou, não quero respostas ou algo do tipo, quero apenas uma ajuda com esse erro…

5 Respostas

M

ArrayIndexOutOfBoundsException significa que você tentou acessar uma posição inválida no array e essa posição foi a -1.

Caso você queira continuar com esse trabalho, dê uma estudada em têoria dos grafos e procure sobre o algorítimo A*(A estrela)

Não vou comentar sobre o código, pois a lógica está errada, mas tenho um projeto aqui que faz algo semelhante assim que achar eu posto novamente.

Nivekzin

magostta:
ArrayIndexOutOfBoundsException significa que você tentou acessar uma posição inválida no array e essa posição foi a -1.

Caso você queira continuar com esse trabalho, dê uma estudada em têoria dos grafos e procure sobre o algorítimo A*(A estrela)

Não vou comentar sobre o código, pois a lógica está errada, mas tenho um projeto aqui que faz algo semelhante assim que achar eu posto novamente.

Obrigado cara, qlqr ajuda é bem-vinda… irei olhar essa teoria no qual vc falou… logo logo a noite estou de volta e comento se deu tudo certo ou não… e obrigado novamente…

M
import java.util.ArrayList;


public class Busca {
	private String[][] mapa;
	
	public static void main(String[] args) {
		//x solido
		//_ não solido
		//i inicio
		//f fim
		
		String[][] mapa = { {"i","_","_","_"}, 
							{"x","x","x","_"},
							{"_","_","_","_"},
							{"_","x","x","x"},
							{"_","_","_","f"}};
		
		new Busca( mapa );
	}
	
	public Busca( String[][] mapa ) {
		this.mapa = mapa;
		int[] cordInicio = getPosInicio();
		
		if(cordInicio != null)
			percorre( null, cordInicio[0], cordInicio[1] );
	}

	private int[] getPosInicio(){
		for (int i = 0; i < mapa.length; i++)
			for (int j = 0; j < mapa[i].length; j++)
				if( "i".equals(mapa[i][j]) )
					return new int[]{i, j};

		return null;
	}
	
	private boolean isPosValida( int linha, int coluna, ArrayList<String> caminho ){
		if( linha  <  0 ||
			coluna <  0 ||
			linha  >= mapa.length ||
			coluna >= mapa[linha].length ||
			"x".equals(mapa[linha][coluna]) || 
			caminho.contains(linha + "," + coluna) )
			return false;
		return true;
	}
	
	@SuppressWarnings("unchecked")
	private void percorre( ArrayList<String> caminho, int linha, int coluna ){
		
		if( caminho == null )
			caminho = new ArrayList<String>();
			
		caminho.add( linha + "," + coluna );

		if( "f".equals(mapa[linha][coluna]) )
			System.out.println( caminho );
		else{
			if( isPosValida(linha-1, coluna, caminho) )
				percorre( (ArrayList<String>) caminho.clone(), linha - 1, coluna );
			if( isPosValida(linha, coluna-1, caminho))
				percorre( (ArrayList<String>) caminho.clone(), linha, coluna - 1 );
			if( isPosValida(linha, coluna+1, caminho))
				percorre( (ArrayList<String>) caminho.clone(), linha, coluna + 1 );
			if( isPosValida(linha+1, coluna, caminho))
				percorre( (ArrayList<String>) caminho.clone(), linha + 1, coluna );
		}
	}
}

Não é um codigo que você possa dizer -Nossa que código otimizado e efetivo

Mas resolve o problema :smiley:

G

//adiciona essa linha

public static int walk(int x, int y, String direc){ maze[x][y] = "1"; if ((x == 0) or (y == 0)) return wall;

pq no lugar de “String direc” vc não usa um Enum?

acho q em java usa-se pouco enum e mt constante.

ViniGodoy

Site sobre o A*: http://www.policyalmanac.org/games/aStarTutorial_port.htm

Criado 29 de fevereiro de 2012
Ultima resposta 1 de mar. de 2012
Respostas 5
Participantes 4