﻿ java – 在二维数组中查找可用的“数字” - 代码日志

#### java – 在二维数组中查找可用的“数字”

1的所有东西都是“墙”,这意味着你无法通过它. 2是你输入数组或地图的入口,如果你愿意的话. 3是我们需要找到的东西.以下是地图的示例：

``````1111111
1  3131
2 11111
1    31
1111111
``````

``````int treasureAmount = 0;
Point entrance = new Point(0,0);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; i++){
if(map[i][j] == 2){
entrance.x =i;
entrance.y =j;
}

}
``````

O(n ^ 2)你不能做得更好.读取阵列需要花费很多时间.但是你可以进行深度优先搜索,找到数组中可达到的3.这是伪代码.

``````main()
{
read array and mark the entrance as ent.x and ent.y and also an array threex[] and threey[] that stores all the exit position.
boolean visited[][]; //stores whether array[i][j] is reachable or not.
dfs(ent.x,ent.y);
for each element in three arrays
{
if(visited[threex[i]][threey[i]]) print ("Reachable");
else print("not reachable", threex[i], threey[i]);
}
}
int dx[]={1,0,-1,0},dy[]={0,1,0,-1}; // dx[i], dy[i] tells whether to move in E,N,W,S respectively.
dfs(int x,int y)
{
visited[x][y]=true;
for(i=0;i<4;i++)//move in all directions
{
int newx=x+dx[i],newy=y+dy[i];
//check if this is within the array boundary
if(newx>=0&&newx<N && newy>=0&&newy<N)
if(!visited[newx][newy] && array[newx][newy]!=1) // check if the node is unvisited and that it is pemissible
dfs(newx,newy);
}
}
``````