multidimensional-array - 二维数组遍历以获得不同的 7 位数字组合
问题描述
我从一本面试准备书中遇到了一个棘手的问题。你有一个包含整数 1 到 9 的 3 x 3 矩阵,如下所示
1 2 3
4 5 6
7 8 9
您如何获得唯一的 7 位数字组合,其中第一个数字都以 4 开头(矩阵 [1] [0])。遍历就像棋盘上的车一样。水平或垂直方向的一种方式...(顺便说一句,拥有 4125874 是有效的 7 位组合)。
我尝试编写一些代码并在此处使用布尔访问标志进行常规 2D 矩阵遍历以获得答案并将每个组合存储在 hashSet 中以确保唯一性,但我被卡住了。任何能让我代码正常工作的评论、提示和代码修订都将不胜感激。
class Ideone
{
void dfs(int[][] matrix, boolean visited) //considered dfs with a boolean visited flag but I am stuck. I want to make my solution recursive
{
boolean visited = false;
}
public static HashSet<String> get7DigitCombo(int[][] matrix)
{
String result = "";
int[][] cache = matrix.clone();
Set<String> comboSet = new HashSet<String>();
boolean visited = false;
int resultStart = matrix[1][0];
for(int row = 1; row < matrix.length; row++)
{
for(int col = 0; col < matrix[0].length; col++)
{
if (visited == false & result.length < 7)
{
result += "" + (matrix[row + 1][col] || matrix[row -1][col] || matrix[row][col+1] || matrix[row][col-1]);
}
}
}
comboSet.add(result);
return comboSet;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int[][] matrix = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
};
HashSet<String> comboSet = get7DigitCombo(matrix);
System.out.print(comboSet);
}
}
解决方案
这是一个吃豆人问题。您必须查找或定义每个矩阵值的邻居。然后穿过矩阵,使每个矩阵值的邻居都闲置。它通常使用递归函数来解决。我认为您必须使用不同的方法从头开始更改代码。
推荐阅读
- swift - 添加左键和标题后右键不显示
- javascript - 使用 jQuery Ajax 和 PHP 上传裁剪的图像
- java - 如何验证成员是否为管理员?
- vue.js - 在组件之间发送数据(vue 中的事件监听器?)
- ios - iOS 13:UICollectionViewCompositionalLayout 的缓存?
- matlab - 将主矩阵中的最佳结果保存到另一个矩阵中
- javascript - Google 跟踪代码管理器在我的页面底部创建空按钮
- reactjs - 如何更新 Bootstrap 模态内容?
- python-3.x - 这个函数声明中 -> List[int] 是什么意思?
- python - 在 python 中加载一个 xgboost 模型,该模型由 R 中的 `xgboost::save()` 保存