LeetCode 35. Valid Sudoku
2014-06-24 02:34
309 查看
数独规则:
考察每行、每列、以及九个九宫格中的任意一个(题中已用粗线分割),都不包含重复的数字(即至多只有一个1, 2, 3, ..., 9)
代码:
class Solution
{
public:
bool isValidSudoku(vector<vector<char> > &board)
{
vector<int> cnt(9, 0);
for (int i = 0; i < 9; ++ i)
{
cnt.assign(9, 0);
for (int j = 0; j < 9; ++ j)
{
if (board[i][j] == '.')
{
continue;
} else if ( ++ cnt[board[i][j] - '1'] > 1)
{
return false;
}
}
}
for (int j = 0; j < 9; ++ j)
{
cnt.assign(9, 0);
for (int i = 0; i < 9; ++ i)
{
if (board[i][j] == '.')
{
continue;
} else if ( ++ cnt[board[i][j] - '1'] > 1)
{
return false;
}
}
}
return square_judge(0, 0, board) && square_judge(0, 3, board) && square_judge(0, 6, board)
&& square_judge(3, 0, board) && square_judge(3, 3, board) && square_judge(3, 6, board)
&& square_judge(6, 0, board) && square_judge(6, 3, board) && square_judge(6, 6, board);
}
private:
bool square_judge(int x, int y, const vector<vector<char> > &board)
{
vector<int> cnt(9, 0);
for (int i = 0; i < 3; ++ i)
{
for (int j = 0; j < 3; ++ j)
{
if (board[x+i][y+j] == '.')
{
continue;
} else if ( ++ cnt[board[x+i][y+j] - '1'] > 1)
{
return false;
}
}
}
return true;
}
};
考察每行、每列、以及九个九宫格中的任意一个(题中已用粗线分割),都不包含重复的数字(即至多只有一个1, 2, 3, ..., 9)
代码:
class Solution
{
public:
bool isValidSudoku(vector<vector<char> > &board)
{
vector<int> cnt(9, 0);
for (int i = 0; i < 9; ++ i)
{
cnt.assign(9, 0);
for (int j = 0; j < 9; ++ j)
{
if (board[i][j] == '.')
{
continue;
} else if ( ++ cnt[board[i][j] - '1'] > 1)
{
return false;
}
}
}
for (int j = 0; j < 9; ++ j)
{
cnt.assign(9, 0);
for (int i = 0; i < 9; ++ i)
{
if (board[i][j] == '.')
{
continue;
} else if ( ++ cnt[board[i][j] - '1'] > 1)
{
return false;
}
}
}
return square_judge(0, 0, board) && square_judge(0, 3, board) && square_judge(0, 6, board)
&& square_judge(3, 0, board) && square_judge(3, 3, board) && square_judge(3, 6, board)
&& square_judge(6, 0, board) && square_judge(6, 3, board) && square_judge(6, 6, board);
}
private:
bool square_judge(int x, int y, const vector<vector<char> > &board)
{
vector<int> cnt(9, 0);
for (int i = 0; i < 3; ++ i)
{
for (int j = 0; j < 3; ++ j)
{
if (board[x+i][y+j] == '.')
{
continue;
} else if ( ++ cnt[board[x+i][y+j] - '1'] > 1)
{
return false;
}
}
}
return true;
}
};
相关文章推荐
- LeetCode: Path Sum II
- [LeetCode]Linked List Cycle
- 【LeetCode】Candy
- LeetCode: Reorder List [143]
- [leetcode] Remove Duplicates from Sorted List II
- leetcode[96] Binary Tree Inorder Traversal
- Leetcode: Path Sum
- 【leetcode】Climbing Stairs
- LeetCode:Reverse words in a String
- 【LeetCode-面试算法经典-Java实现】【023-Merge k Sorted Lists(合并k个排好的的单链表)】
- 【LeetCode】119. Pascal's Triangle II
- LeetCode 190: Reverse Bits
- java 前缀树实现 leetcode 208: Implement Trie (Prefix Tree)
- leetcode 7. Reverse Integer
- 1.TwoSum-Leetcode
- leetcode_Search a 2D Matrix
- LeetCode - 113. Path Sum II
- leetcode 3. Longest Substring Without Repeating Characters
- Leetcode-166. Fraction to Recurring Decimal
- [Leetcode] Search in Rotated Sorted Array