Leetcode 52. N皇后 II

xiaoxiao2021-02-28  61

和上一题一摸一样,只是返回上一题答案的size

class Solution { public: int ans; bool vis[1005][1005] = {}, row[1005] = {}; void dfs(int col, int &n) { if (col == n) { ++ans; return; } for (int i = 0; i < n; ++i) if (!row[i] && !vis[i][col]) { vector<pair<int, int>> tt; row[i] = 1; int k = 1; while (col + k < n && i + k < n) { if (!vis[i + k][col + k]) tt.push_back(make_pair(i + k, col + k)); ++k; } k = 1; while (col + k <n && i - k >= 0) { if (!vis[i - k][col + k]) tt.push_back(make_pair(i - k, col + k)); ++k; } for (auto &x : tt) vis[x.first][x.second] = 1; dfs(col + 1, n); for (auto &x : tt) vis[x.first][x.second] = 0; row[i] = 0; } } int totalNQueens(int n) { dfs(0, n); return ans; } };
转载请注明原文地址: https://www.6miu.com/read-2630969.html

最新回复(0)