首页 > 代码库 > leetcode-sudoku solver

leetcode-sudoku solver

这道题让我切身体会了引用传递和值传递这两种方式的巨大差异。

在isValid子函数中,若采用引用传递将board传参,程序运行时间在0.068左右,可以AC.

若采用值传递将board传参,程序运行时间在2.011左右,直接TLE。

一切只因为一个"&". 引用传递与值传递效率差异可以如此明显。

 1 class Solution { 2 public: 3     void solveSudoku(vector<vector<char> > &board) { 4         dfs(board, 0, 0); 5     } 6     bool dfs(vector<vector<char>> &board,int i,int j) 7     { 8         if (j >= 9) return dfs(board,i+1,0); 9         if (i == 9) return true;10         if (board[i][j] == .)11         {12             for (int k = 1; k <= 9; k++)13             {14                 board[i][j] = char(k + 0);15                 if (isValid(board, i, j))16                 {17                     if (dfs(board, i, j + 1)) return true;18                 }19                 board[i][j] = .;20             }21         }22         else return dfs(board,i,j+1);23         return false;24     }25     bool isValid(vector<vector<char>> &board,int i,int j)//在board作为参数时,有&和没&,时间效率差别非常大!!!26     {27         for (int k = 0; k < 9; k++)28         {29             if (k != j&&board[i][j] == board[i][k]) return false;30         }31         for (int k = 0; k < 9; k++)32         {33             if (k != i&&board[i][j] == board[k][j]) return false;34         }35         for (int row = i / 3 * 3; row < i / 3 * 3 + 3; row++)//(i,j)所在的小九宫格36         {37             for (int col = j / 3 * 3; col < j / 3 * 3 + 3; col++)38             {39                 if ((row != i || col != j) && board[i][j] == board[row][col])40                     return false;41             }42         }43         return true;44     }45 };

 

leetcode-sudoku solver