千锋教育-做有情怀、有良心、有品质的职业教育机构

400-811-9990
手机站
千锋教育

千锋学习站 | 随时随地免费学

千锋教育

扫一扫进入千锋手机站

领取全套视频
千锋教育

关注千锋学习站小程序
随时随地免费学习课程

上海
  • 北京
  • 郑州
  • 武汉
  • 成都
  • 西安
  • 沈阳
  • 广州
  • 南京
  • 深圳
  • 大连
  • 青岛
  • 杭州
  • 重庆
当前位置:杭州千锋IT培训  >  技术干货  >  算法题---有效的数独

算法题---有效的数独

来源:千锋教育
发布人:qyf
时间: 2023-01-16 17:07:37

算法题---有效的数独

  题目

  判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。

  数字 1-9 在每一行只能出现一次。

  数字 1-9 在每一列只能出现一次。

  数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。

  示例 1:

  输入:

  [

  ["5","3",".",".","7",".",".",".","."],

  ["6",".",".","1","9","5",".",".","."],

  [".","9","8",".",".",".",".","6","."],

  ["8",".",".",".","6",".",".",".","3"],

  ["4",".",".","8",".","3",".",".","1"],

  ["7",".",".",".","2",".",".",".","6"],

  [".","6",".",".",".",".","2","8","."],

  [".",".",".","4","1","9",".",".","5"],

  [".",".",".",".","8",".",".","7","9"]

  ]

  输出: true

  示例 2:

  输入:

  [

  ["8","3",".",".","7",".",".",".","."],

  ["6",".",".","1","9","5",".",".","."],

  [".","9","8",".",".",".",".","6","."],

  ["8",".",".",".","6",".",".",".","3"],

  ["4",".",".","8",".","3",".",".","1"],

  ["7",".",".",".","2",".",".",".","6"],

  [".","6",".",".",".",".","2","8","."],

  [".",".",".","4","1","9",".",".","5"],

  [".",".",".",".","8",".",".","7","9"]

  ]

  输出: false

  解释: 除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。

  但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。

  示例 3:

  输入: [1,3,5,6], 7

  输出: 4

  示例 4:

  输入: [1,3,5,6], 0

  输出: 0

  思路解析

  一次遍历法

  这道题因为需要判断数值是否存在,所以用Hash Map是一个很好的选择。 因为每一行、每一列、每一格都是需要单独进行判断的,所以需要建立三个长度为9的HashMap数组,分别存放行、列、格的数值。

  通过一个二层循环遍历这个9*9的数组,把当前格的数值存放到对应的HashMap中,判断之前是否已经存放过了,如果已经存放过那就退出,返回false,如果是.的话那就跳过,这样只需要遍历一边就可以了。

  代码实现

  //时间复杂度:O(n)

  //空间复杂度:O(1)

  class Solution {

  public boolean isValidSudoku(char[][] board) {

  HashMap[] row = new HashMap[9];

  HashMap[] column = new HashMap[9];

  HashMap[] box = new HashMap[9];

  for (int i = 0; i < 9; i++) {

  row[i] = new HashMap(9);

  column[i] = new HashMap(9);

  box[i] = new HashMap(9);

  }

  for (int i = 0; i < 9; i++) {

  for (int j = 0; j < 9; j++) {

  if (board[i][j] == '.') {

  continue;

  }

  int boxIndex=i / 3 * 3 + j / 3;

  if ((boolean) row[i].getOrDefault(board[i][j], true)) {

  return false;

  }

  if ((boolean) column[j].getOrDefault(board[i][j], true)) {

  return false;

  }

  if ((boolean) box[boxIndex].getOrDefault(board[i][j], true)) {

  return false;

  }

  row[i].put(board[i][j], false);

  column[j].put(board[i][j], false);

  box[boxIndex].put(board[i][j], false);

  }

  }

  

  return true;

  }

  }

声明:本站稿件版权均属千锋教育所有,未经许可不得擅自转载。

猜你喜欢LIKE

vue3.0和2.0的区别

2023-04-20

接口测试属于功能测试吗

2023-04-12

软件测试流程分几个阶段?

2023-04-11

最新文章NEW

学习c语言用什么软件

2023-04-14

hadoop需要什么基础

2023-04-10

java框架是什么意思

2023-03-20

相关推荐HOT

更多>>

快速通道 更多>>

最新开班信息 更多>>

网友热搜 更多>>