Share my CPP very short solution~


  • 1
    O
    class Solution {
      bool ok = false;
    public:
      void solveSudoku(vector<vector<char>>& board) {
        for (int i = 0; i < 9; i++) for (int j = 0; j < 9; j++) if (board[i][j] == '.') {
          set<char> st;
          for (int k = 0; k < 9; k++) {
            st.insert(board[k][j]);
            st.insert(board[i][k]);
          }
          int tx = (i / 3) * 3, ty = (j / 3) * 3;
          for (int k1 = 0; k1 < 3; k1++) for (int k2 = 0; k2 < 3; k2++) st.insert(board[tx + k1][ty + k2]);
          for (char k = '1'; k <= '9'; k++) if (st.find(k) == st.end()) {
            board[i][j] = k;
            solveSudoku(board);
            if (ok) return;
            board[i][j] = '.';
          }
          if (board[i][j] == '.') return;
        }
        ok = true;
      }
    };

  • 0
    C

    you just need only one if(ok) return; in solveSudoku(board); if(ok) return; board[i][j] = '.'; other if(ok) return; can be removed, because it will never be execute. PS. your solution is good!


  • 0
    O

    Thanks, my code is not clean enough!
    Modified.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.