gpt4 book ai didi

java - 如何在矩阵中找到从一点到另一点的逃生路线?

转载 作者:行者123 更新时间:2023-12-02 06:58:21 25 4
gpt4 key购买 nike

这不是作业。这只是一道练习题。

给定一个矩阵,找出从 (0,0) 到 (N,N) 的可能逃生路线的数量。 你不能沿对角线移动。

“0”位置代表开放单元,而“1”代表阻塞单元。我从 (0,0) 开始旅程,必须到达 (N,N)。

输入格式

第一行是一个奇数正整数 T (<= 85),表示矩阵的大小。接下来是 T 行,每行包含 T 个空格分隔的数字,即“0”或“1”。

输出格式

输出我可以从 (0,0) 逃逸到 (N,N) 的方式数。

示例输入

7
0 0 1 0 0 1 0
1 0 1 1 0 0 0
0 0 0 0 1 0 1
1 0 1 0 0 0 0
1 0 1 1 0 1 0
1 0 0 0 0 1 0
1 1 1 1 0 0 0

示例输出

4

根据我的解决方案,我采取了四个方向 - 左(l)、右(r)、上(u)、下(d)。

问题是它给出了错误的答案或 stackoverflow 错误。缺少什么?

这是这个问题的最佳解决方案吗?

我的解决方案(Java)

import java.io.BufferedReader;
import java.io.InputStreamReader;

class testclass {
int no_of_escapes = 0 ;
int[][] arr;
int matrixlength;
public static void main(String[] args) throws Exception
{

testclass obj = new testclass();
obj.checkpaths(0,0,"");
System.out.print(obj.no_of_escapes);

}//main

testclass()
{
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
matrixlength =Integer.parseInt(br.readLine());
arr = new int[matrixlength][matrixlength];
for( int k = 0; k < matrixlength; k++){

String str = br.readLine();
int count = 0;
for(int j=0 ; j< ((2*matrixlength)-1); j++){
int v = (int)str.charAt(j) - 48;
if(v == -16){}
else{
arr[k][count] = v;
count++;
}

}//for j

}//for k

}
catch(Exception e){}
}

public void checkpaths(int m, int n,String direction){

if((m == matrixlength -1) && (n == matrixlength-1))
{
no_of_escapes = no_of_escapes +1;
return;
}

if(!direction.equals("l"))
{
if(m < matrixlength && n < matrixlength)
{
if((n+1) < matrixlength )
{
if(arr[m][n+1]==0 )
{
checkpaths(m,n+1,"r");
}
}
}
}

if(!direction.equals("u"))
{
if((m+1) < matrixlength )
{
if(arr[m+1][n]==0 )
{
checkpaths(m+1,n,"d");
}
}
}

if(!direction.equals("r"))
{
if(m < matrixlength && n < matrixlength)
{
if((n+1) < matrixlength )
{
if(arr[m][n+1]==0 )
{
checkpaths(m,n+1,"l");
}
}
}
}

if(!direction.equals("d"))
{
if((m-1)>=0)
{
if(arr[m-1][n]==0 )
{
checkpaths(m-1,n,"u");
}

}

}


}
}//class

最佳答案

我将保留第二个二维 boolean 数组来标记您已经访问过的单元格,如下面的代码片段所示。我还简化了代码的其他一些部分,以减少代码重复。

当然,您需要在构造函数中初始化 visited,就像初始化 arr 一样,使用 visited = new boolean[matrixLength][matrixLength] .

int[][] arr;
boolean[][] visited;
final int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

public boolean isValid(int x, int y) {
return 0 <= x && x < matrixLength
&& 0 <= y && y < matrixLength
&& arr[x][y] == 0
&& !visited[x][y];
}


public void checkPaths(int x, int y) {
if (x == matrixLength-1 && y == matrixLength-1) {
no_of_escaped++;
} else {
for (int[] d : directions) {
if (isValid(x + d[0], y + d[1])) {
visited[x + d[0]][y + d[1]] = true;
checkPaths(x + d[0], y + d[1]);
visited[x + d[0]][y + d[1]] = false;
}
}
}
}

关于java - 如何在矩阵中找到从一点到另一点的逃生路线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17010113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com