Skip to content

Latest commit

 

History

History
120 lines (99 loc) · 3.24 KB

36.有效的数独.md

File metadata and controls

120 lines (99 loc) · 3.24 KB

36. 有效的数独

url

题目

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

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

lc-shudu-9RLJZZ

方法

code

js

let isValidSudoku = board => {
    // 记录某行,某位数字是否已经被摆放
    let row = Array(9).fill(false);
    // 记录某列,某位数字是否已经被摆放
    let col = Array(9).fill(false);
    // 记录某3x3宫格内,某位数字是否已经被摆放
    let block = Array(9).fill(false);
    // 初始化 js的二维数组真麻烦
    row.forEach((val, idx,arr) => {
        arr[idx] = Array(9).fill(false);
        col[idx] = Array(9).fill(false);
        block[idx] = Array(9).fill(false);
    });
    for (let i = 0; i < 9; i++) {
        for (let j = 0; j < 9; j++) {
            if (board[i][j] !== ".") {
                let num = board[i][j] - '1';
                let blockIdx = Math.floor(i / 3) * 3 + Math.floor(j / 3);
                if (row[i][num] || col[j][num] || block[blockIdx][num]){
                    return false;
                }
                else {
                    row[i][num] = true;
                    col[j][num] = true;
                    block[blockIdx][num] = true;
                }
            }
        }
    }

    return true;
}

go

func isValidSudoku(board [][]byte) bool {
	row := make([][]byte, 9)
	col := make([][]byte, 9)
	block := make([][]byte, 9)
	for i := 0; i < 9; i++ {
		for j := 0; j < 9; j++ {
			if board[i][j] != '.' {
				num := board[i][j] - '1'
				blockIdx := i / 3 * 3 + j / 3
				if row[i][num] == 0 || col[j][num] == 0 || block[blockIdx][num] == 0 {
					return false
				} else {
					row[i][num] = 0
					col[j][num] = 0
					block[blockIdx][num] = 0
				}
			}
		}
	}
	return true
}

java

class Solution {
    public boolean isValidSudoku(char[][] board) {
        // 记录某行,某位数字是否已经被摆放
        boolean[][] row = new boolean[9][9];
        // 记录某列,某位数字是否已经被摆放
        boolean[][] col = new boolean[9][9];
        // 记录某3x3宫格内,某位数字是否已经被摆放
        boolean[][] block = new boolean[9][9];

        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (board[i][j] != '.') {
                    int num = board[i][j] - '1';
                    int blockIdx = i / 3 * 3 + j / 3;
                    System.out.println(i + " " + j + " " + blockIdx + " " + num);
                    System.out.println(row[i][num] + " " + col[j][num] + " " + block[blockIdx][num]);
                    if (row[i][num] || col[j][num] || block[blockIdx][num]) {
                        return false;
                    } else {
                        row[i][num] = true;
                        col[j][num] = true;
                        block[blockIdx][num] = true;
                    }
                }
            }
        }
        return true;
    }
}