标签:
问题描述:给定9x9矩阵,看是是否是有效数独,不用全部都填上数字,可以为.
算法分析:这道题就是判断,不难,有效数独三个充分条件,行,列,3*3子矩阵,都要满足数字不能重复。
1 public boolean isValidSudoku(char[][] board) 2 { 3 if(board == null || board.length != 9 || board[0].length != 9) 4 { 5 return false; 6 } 7 8 //判断行 9 for(int i = 0; i < 9; i ++) 10 { 11 boolean[] m = new boolean[9]; 12 for(int j = 0; j < 9; j ++) 13 { 14 if(board[i][j] != ‘.‘) 15 { 16 //if(m[(int)board[i][j]])这样写是错误的,因为(int)‘1‘不等于1. 17 if(m[(int)(board[i][j]-‘1‘)]) 18 { 19 return false; 20 } 21 m[(int)(board[i][j]-‘1‘)] = true; 22 } 23 } 24 } 25 26 //判断列 27 for(int i = 0; i < 9; i ++) 28 { 29 boolean[] m = new boolean[9]; 30 for(int j = 0; j < 9; j ++) 31 { 32 if(board[j][i] != ‘.‘) 33 { 34 if(m[(int)(board[j][i]-‘1‘)]) 35 { 36 return false; 37 } 38 m[(int)(board[j][i]-‘1‘)] = true; 39 } 40 } 41 } 42 43 //判断3*3矩阵,总共有9个 44 for(int k = 0; k < 9; k ++) 45 { 46 boolean[] m = new boolean[9]; 47 for(int i = k/3*3; i < k/3*3 + 3; i ++) 48 { 49 for(int j = k%3*3; j < k%3*3 + 3; j ++) 50 { 51 if(board[i][j] != ‘.‘) 52 { 53 if(m[(int)(board[i][j]-‘1‘)]) 54 { 55 return false; 56 } 57 m[(int)(board[i][j]-‘1‘)] = true; 58 } 59 } 60 } 61 } 62 63 return true; 64 }
标签:
原文地址:http://www.cnblogs.com/masterlibin/p/5577482.html