看了网上答案,发现一个很有趣的问题,check函数里形参board是传值时(即&board)速度很快,能过large,去掉这个&后就过不了large了,是不是因为没有传值的话每次需要复制这样耗了时间了呢
1 class Solution { 2 public: 3 bool check(int x, int y, vector<vector<char>> &board) { 4 bool flag[9] = {false}; 5 for (int i = 0; i < 9; i++) 6 if (board[x][i] != '.') 7 if (!flag[board[x][i]-'1']) flag[board[x][i]-'1'] = true; 8 else return false; 9 memset(flag, false, 9); 10 for (int i = 0; i < 9; i++) 11 if (board[i][y] != '.') 12 if (!flag[board[i][y]-'1']) flag[board[i][y]-'1'] = true; 13 else return false; 14 memset(flag, false, 9); 15 int xx = x/3*3; 16 int yy = y/3*3; 17 for (int i = 0; i < 3; i++) 18 for (int j = 0; j < 3; j++) 19 if (board[xx+i][yy+j] != '.') 20 if (!flag[board[xx+i][yy+j]-'1']) flag[board[xx+i][yy+j]-'1'] = true; 21 else return false; 22 return true; 23 } 24 bool dfs(vector<vector<char>> &board) { 25 for (int i = 0; i < 9; i++) { 26 for (int j = 0; j < 9; j++) { 27 if (board[i][j] == '.') { 28 for (char k = '1'; k <= '9'; k++) { 29 board[i][j] = k; 30 if (check(i, j, board) && dfs(board)) return true; 31 board[i][j] = '.'; 32 } 33 return false; 34 } 35 } 36 } 37 return true; 38 } 39 void solveSudoku(vector<vector<char> > &board) { 40 // Start typing your C/C++ solution below 41 // DO NOT write int main() function 42 dfs(board); 43 } 44 };
C#
1 public class Solution { 2 public void SolveSudoku(char[,] board) { 3 dfs(board); 4 5 } 6 public bool dfs(char[,] board) { 7 for (int i = 0; i < 9; i++) { 8 for (int j = 0; j < 9; j++) { 9 if (board[i, j] == '.') { 10 for (char k = '1'; k <= '9'; k++) { 11 board[i, j] = k; 12 if (check(i, j, board) && dfs(board)) return true; 13 board[i, j] = '.'; 14 } 15 return false; 16 } 17 } 18 } 19 return true; 20 } 21 public bool check(int x, int y, char[,] board) { 22 bool[] flag = new bool[9]; 23 for (int i = 0; i < 9; i++) { 24 if (board[x, i] != '.') { 25 if (!flag[board[x, i] - '1']) flag[board[x, i] - '1'] = true; 26 else return false; 27 } 28 } 29 flag = new bool[9]; 30 for (int i = 0; i < 9; i++) 31 if (board[i, y] != '.') 32 if (!flag[board[i, y]-'1']) flag[board[i, y]-'1'] = true; 33 else return false; 34 flag = new bool[9]; 35 int xx = x/3*3; 36 int yy = y/3*3; 37 for (int i = 0; i < 3; i++) 38 for (int j = 0; j < 3; j++) 39 if (board[xx+i, yy+j] != '.') 40 if (!flag[board[xx+i, yy+j]-'1']) flag[board[xx+i, yy+j]-'1'] = true; 41 else return false; 42 return true; 43 } 44 }