我在学习上我自己的编程与书为初学者在矩阵相邻数字的区域。我的章阵列后,最后的任务是:查找最大使用DFS算法
// Find the biggest area of adjacent numbers in this matrix:
int[][] matrix = {
{1,3,2,2,2,4},
{3,3,3,2,4,4},
{4,3,1,2,3,3}, // --->13 times '3';
{4,3,1,3,3,1},
{4,3,3,3,1,1}
作为一个暗示我有 - 使用DFS或BFS算法。在阅读了他们的资料后,我看到很多他们的实现,但我对这个想法有所了解,但对于一个初学者来说,这实在太过分了。我为我的任务找到了解决方案,在我运行程序很多次后,我明白了它的工作原理,现在我可以自己解决问题。虽然,我很高兴,这个解决方案帮助我了解递归,我想知道,可以将下面的代码迭代的方式进行修改,如果这样你就可以给我提示怎么办呢?先谢谢你。
public class Practice {
private static boolean[][] visited = new boolean[6][6];
private static int[] dx = {-1,1,0,0};
private static int[] dy = {0,0,-1,1};
private static int newX;
private static int newY;
public static void main(String[] args){
// Find the biggest area of adjacent numbers in this matrix:
int[][] matrix = {
{1,3,2,2,2,4},
{3,3,3,2,4,4},
{4,3,1,2,3,3}, // --->13 times '3';
{4,3,1,3,3,1},
{4,3,3,3,1,1}
};
int current = 0;
int max = 0;
for (int rows = 0; rows < matrix.length;rows++){
for(int cols = 0; cols < matrix[rows].length;cols++){
if (visited[rows][cols] == false){
System.out.printf("Visited[%b] [%d] [%d] %n", visited[rows]
[cols],rows,cols);
current = dfs(matrix,rows,cols,matrix[rows][cols]);
System.out.printf("Current is [%d] %n", current);
if(current > max){
System.out.printf("Max is : %d %n ", current);
max = current;
}
}
}
}
System.out.println(max);
}
static int dfs(int[][] matrix,int x, int y, int value){
if(visited[x][y]){
System.out.printf("Visited[%d][%d] [%b] %n",x,y,visited[x][y]);
return 0;
} else {
visited[x][y] = true;
int best = 0;
int bestX = x;
int bestY = y;
for(int i = 0; i < 4;i++){
//dx = {-1,1,0,0};
//dy = {0,0,-1,1};
int modx = dx[i] + x;
System.out.printf(" modx is : %d %n", modx);
int mody = dy[i] + y;
System.out.printf(" mody is : %d %n", mody);
if(modx == -1 || modx >= matrix.length || mody == -1 || mody >=
matrix[0].length){
continue;
}
if(matrix[modx][mody] == value){
System.out.printf("Value is : %d %n",value);
int v = dfs(matrix,modx,mody,value);
System.out.printf(" v is : %d %n",v);
best += v;
System.out.printf("best is %d %n",best);
}
newX = bestX;
System.out.printf("newX is : %d %n",newX);
newY = bestY;
System.out.printf("newY is : %d %n",newY);
}
System.out.printf("Best + 1 is : %d %n ",best + 1);
return best + 1;
}
}
}
注意,通常y是用于行列和X;因此,您可以使用'modx> = matrix [0] .length'和'mody> = matrix.length',而不是反之。 – tucuxi