bool isValid(int x, int y, vector<vector<int>> &arr)
{
if (x >= 0 && x <= arr.size() && y >= 0 && y <= arr[0].size() && arr[x][y] == 1)
return true;
return false;
}
I am getting segmentation fault on this ( x <= arr.size() and y<=arr[0].size() ) of the code.
Can you guys please explain why I am getting this even if I am not accessing the out of bound value and I am just comparing it.
Packing too many conditions into one is not always good. Splitting it up in several conditions can help with debugging. Simple code is not always less code.
bool isValid(int x, int y, vector<vector<int>> &arr) {
// first index is ok?
if (x < 0) return false;
if (x >= arr.size()) return false;
// only now you can access arr[x]
if (y < 0) return false;
if (y >= arr[x].size()) return false;
// both are ok
return arr[x][y] == 1;
}
In your code you are checking arr[0] not arr[x], when all inner vectors are of same size you can consider to use a different data structure. Even when you know that all inner vectors of same size you should nevertheless check arr[x] not arr[0]. Also consider to use size_t (it is unsigned) for the indices, then you can remove the checks for <0.
Your code can segfault because the last valid index is size -1 not size and because arr[0] does not necessarily have same number of elements as arr[x].
What if x == 0 and arr.size() == 0?
In this case, you'll fail on accessing arr[0] inside the y <= arr[0].size() expression, because you are trying to access the vector object present in arr[0] while such thing does not exist.
To be more general, you have to note that accessing arr[x][y] is not valid if x == arr.size() or y == arr[x].size(), but you're allowing such situation by x <= arr.size() and y <= arr[0].size() in your conditions. Your function would finally look like something like this:
bool isValid(int x, int y, vector<vector<int>> &arr)
{
if (x >= 0 && x < arr.size() && y >= 0 && y < arr[x].size() && arr[x][y] == 1)
return true;
return false;
}
why I am getting this even if I am not accessing the out of bound value and I am just comparing it [?]
Consider y <= arr[0].size(), here you are not just comparing, but accessing the first element of arr and retrieving its size. The problem is that arr may be empty, so that arr[0] would be an access out of bounds.
Also, using <= is an off-by-one error, because size() - 1 is the last valid index.
That function could be rewritten like the following
bool isValid(int x, int y, std::vector<std::vector<int>> const& m)
{
return x >= 0 and x < m.size() and
// ^
y >= 0 and y < m[x].size() and
// ^ ^^^ Are all the same size?
m[x][y] == 1;
}
I have a matrix made out of zeroes and ones. I need a way to see how many "zero blocks" there are. Here's a picture to better illustrate:
In this example there are 4 "zero blocks" divided by the black blocks (ones in the matrix).
As mentioned above, you can use dfs to find components in a graph. Here is a classic code example working on a grid where X means a wall and 0 means free space (black and white squares in your case):
#include <vector>
#include <string>
using Map = std::vector<std::string>;
using BoolMap = std::vector<std::vector<bool>>;
void dfs(BoolMap& visited, int x, int y)
{
if (x < 0 || y < 0 || y >= visited.size() || x >= visited[y].size())
return;
if (visited[y][x])
return;
visited[y][x] = true;
dfs(visited, x - 1, y);
dfs(visited, x + 1, y);
dfs(visited, x, y - 1);
dfs(visited, x, y + 1);
}
int main()
{
Map map;
map.emplace_back("0X00");
map.emplace_back("XXX0");
map.emplace_back("0X0X");
map.emplace_back("0X00");
BoolMap visited(map.size());
for (size_t y = 0; y < map.size(); y++)
{
visited[y].resize(map[y].size());
for (size_t x = 0; x < map[y].size(); x++)
{
// set visited to true if there is a wall
visited[y][x] = (map[y][x] == 'X');
}
}
size_t component_count = 0;
for (size_t y = 0; y < map.size(); y++)
{
for (size_t x = 0; x < map[y].size(); x++)
{
if (!visited[y][x])
{
dfs(visited, x, y);
component_count++;
}
}
}
std::cout << component_count << std::endl;
}
This code can be simplier if you know that your map is always a square one (map.size() can be used instead of map[y].size()). Also I loop through the map twice to check for a walls but if it is not too big there should not be a performance issue.
If you are already working with a boolean matrix and it is okay to change it you can just pass it as a visited parameter and the algorithm will work the same way.
I recommend taking a look at BFS & DFS for graph traversal. You can represent your matrix as a graph where every cell is connected to its neighbors in the 4 directions: North, South, East and west.
If you have a problem, let me know in the comments for more details.
I'm new to the Z3-Solver with API in C++ and want to solve a group of inequalities and find the results.
I've read the answer which written in Python and try to write it in C++, but it repeating prints one model.
5 <= x + y + z <= 16
AND -4 <= x - y <= 6
AND 1 <= y - z <= 3
AND -1 <= x - z <= 7
AND x >= 0 AND y >= 0 AND z >= 0
The inequalities were added into the solver, and have a lot of evaluations.
c is context and s is the solver.
vector<const char*> variables {"x", "y", "z"};
// ...
// till here, s was added into several constraints
while(s.check() == sat){
model m = s.get_model();
cout << m << "\n######\n";
expr tmp = c.bool_val(false);
for(int i = 0; i < variables.size(); ++ i){
tmp = tmp || (m[c.int_const(variables[i])] != c.int_const(variables[i]));
}
s.add(tmp);
}
And the result:
(define-fun z () Int
0)
(define-fun y () Int
2)
(define-fun x () Int
3)
######
(define-fun z () Int
0)
(define-fun y () Int
2)
(define-fun x () Int
3)
######
(define-fun z () Int
0)
...
And it just print one model. I'm not sure where is wrong.
How can I get all models or get one or more convex sets (such as {l1 <= x <= u1 and l2 <= x - y <= u2 and ...}), but not to traverse all evaluations.
BTW, there's a lot tutorials on python(such as this), where I can learn z3 in c++ as the example and api doc. is not easy to get started.
Your "model refutation" loop isn't quite correct. Since you didn't post your whole code, it's hard to tell if there might be other issues, but this is how I would go about it:
#include<vector>
#include"z3++.h"
using namespace std;
using namespace z3;
int main(void) {
context c;
expr_vector variables(c);
variables.push_back(c.int_const("x"));
variables.push_back(c.int_const("y"));
variables.push_back(c.int_const("z"));
expr x = variables[0];
expr y = variables[1];
expr z = variables[2];
solver s(c);
s.add(5 <= x+y+z);
s.add(x+y+z <= 16);
s.add(-4 <= x-y);
s.add(x-y <= 6);
s.add(-1 <= x-z);
s.add(x-z <= 7);
s.add(x >= 0);
s.add(y >= 0);
s.add(z >= 0);
while (s.check() == sat) {
model m = s.get_model();
cout << m << endl;
cout << "#######" << endl;
expr tmp = c.bool_val(false);
for(int i = 0; i < variables.size(); ++i) {
tmp = tmp || (variables[i] != m.eval(variables[i]));
}
s.add(tmp);
}
return 0;
}
This code runs and enumerates all the "concrete" models. From your question, I surmise you're also wondering if you can get "symbolic" models: That's not possible with an SMT solver. SMT solvers only produce concrete (i.e., all ground term) models, so if you need to generalize from them, you'll have to do that outside of the z3 boundary.
The code runs correctly and it does what it is supposed to do, but I was told I could make it faster by using Boolean expressions instead but would not really know where to insert them here. The problem is:
Given a sequence of n points with their coordinates, write a program remote, which calculates the value of the smallest remoteness of a point, which is outside the square. A point is outside the square, if it is neither inner to the square, nor belongs to square contour. If there are no points outside the square, your program has to output 0.
Constraints:
1 ≤ n ≤ 10000 and 1 ≤ a ≤ 1000 ;
Example:
Input:
5 4
1 2
4 6
-3 2
-2 2
4 -1
Output: 5
Could someone suggest me any technique to make the code more efficient?
int remote(int x, int y) {
int z = abs(x) + abs(y);
return z;
}
int main() {
int n, a;
int x;
int y;
cin >> n >> a;
int z=20001;
for (int i = 1; i <= n; i++) {
cin >> x >> y;
if (x > a / 2 || y > a / 2) {
if (z > remote(x, y)) {
z = remote(x, y);
}
}
}
cout << z <<endl;
return 0;
}
For one, you are calling remote twice (in some cases) needlessly.
Consider using this:
#include <algorithm>
z = std::max(z, remote(x, y));
This will also shorten and clarify the code.
Also, it's possible the divisions are slow. Try (after profiling!) replacing
x > a / 2 || y > a / 2
by
(x << 1) > a || (y << 1) > a
Note #Donnie & others claims in the comments that compilers will do the latter optimization, and they are probably correct.
I would like to show you the timings on my machine:
Version 1:
for (int i = 1; i <= n; i++) {
cin >> x >> y;
if (x > a / 2 || y > a / 2) {
if (z > remote(x, y)) {
z = remote(x, y);
}
}
}
Version 2:
for (int i = 1; i <= n; i++) {
cin >> x >> y;
/* if (x > a / 2 || y > a / 2) {
if (z > remote(x, y)) {
z = remote(x, y);
}
}
*/
}
For n=10^5, compiled with -O3 both yield 60ms. Compiled without optimization: both 60ms.
First step for optimizing is to know where your program spends time. Reading/parsing the data is the bottle neck.
You could speed up it a little bit by adding as first line to your main:
ios_base::sync_with_stdio(false);
On my machine I'm down to 20ms.
1) Assign a temporary value to the remote function:
if (x > a / 2 || y > a / 2)
{
const int r = remote(x,y);
if (z > r)
{
z = r;
}
}
2) Replace the call to remote with the contents of remote, removing the overhead of a function call:
if (x > a / 2 || y > a / 2)
{
const int r = abs(x) + abs(y);
if (z > r)
{
z = r;
}
}
3) Replace a / 2 with a constant temporary variable:
const int midpoint = a >> 1;
if (x > midpoint || y > midpoint)
4) Change compiler optimization level to high - for speed.
5) The bottleneck is now in the input statement. Any gain by optimizing the remainder of the loop is wasted by the Input time. There is no more Return On Investment for further changes.
I code the Knight's tour algorithm in c++ using Backtracking method.
But it seems too slow or stuck in infinite loop for n > 7 (bigger than 7 by 7 chessboard).
The question is: What is the Time complexity for this algorithm and how can I optimize it?!
The Knight's Tour problem can be stated as follows:
Given a chess board with n × n squares, find a path for the knight that visits every square exactly once.
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int counter = 1;
class horse {
public:
horse(int);
bool backtrack(int, int);
void print();
private:
int size;
int arr[8][8];
void mark(int &);
void unmark(int &);
bool unvisited(int &);
};
horse::horse(int s) {
int i, j;
size = s;
for (i = 0; i <= s - 1; i++)
for (j = 0; j <= s - 1; j++)
arr[i][j] = 0;
}
void horse::mark(int &val) {
val = counter;
counter++;
}
void horse::unmark(int &val) {
val = 0;
counter--;
}
void horse::print() {
cout << "\n - - - - - - - - - - - - - - - - - -\n";
for (int i = 0; i <= size - 1; i++) {
cout << "| ";
for (int j = 0; j <= size - 1; j++)
cout << setw(2) << setfill ('0') << arr[i][j] << " | ";
cout << "\n - - - - - - - - - - - - - - - - - -\n";
}
}
bool horse::backtrack(int x, int y) {
if (counter > (size * size))
return true;
if (unvisited(arr[x][y])) {
if ((x - 2 >= 0) && (y + 1 <= (size - 1))) {
mark(arr[x][y]);
if (backtrack(x - 2, y + 1))
return true;
else
unmark(arr[x][y]);
}
if ((x - 2 >= 0) && (y - 1 >= 0)) {
mark(arr[x][y]);
if (backtrack(x - 2, y - 1))
return true;
else
unmark(arr[x][y]);
}
if ((x - 1 >= 0) && (y + 2 <= (size - 1))) {
mark(arr[x][y]);
if (backtrack(x - 1, y + 2))
return true;
else
unmark(arr[x][y]);
}
if ((x - 1 >= 0) && (y - 2 >= 0)) {
mark(arr[x][y]);
if (backtrack(x - 1, y - 2))
return true;
else
unmark(arr[x][y]);
}
if ((x + 2 <= (size - 1)) && (y + 1 <= (size - 1))) {
mark(arr[x][y]);
if (backtrack(x + 2, y + 1))
return true;
else
unmark(arr[x][y]);
}
if ((x + 2 <= (size - 1)) && (y - 1 >= 0)) {
mark(arr[x][y]);
if (backtrack(x + 2, y - 1))
return true;
else
unmark(arr[x][y]);
}
if ((x + 1 <= (size - 1)) && (y + 2 <= (size - 1))) {
mark(arr[x][y]);
if (backtrack(x + 1, y + 2))
return true;
else
unmark(arr[x][y]);
}
if ((x + 1 <= (size - 1)) && (y - 2 >= 0)) {
mark(arr[x][y]);
if (backtrack(x + 1, y - 2))
return true;
else
unmark(arr[x][y]);
}
}
return false;
}
bool horse::unvisited(int &val) {
if (val == 0)
return 1;
else
return 0;
}
int main() {
horse example(7);
if (example.backtrack(0, 0)) {
cout << " >>> Successful! <<< " << endl;
example.print();
} else
cout << " >>> Not possible! <<< " << endl;
}
output for the example (n = 7) above is like this:
Since at each step you have 8 possibilities to check and this has to be done for each cell (minus the last one) the time complexity of this algorithm is O(8^(n^2-1)) = O(8^(n^2)) where n is the number of squares on the edges of the checkboard. To be precise this is the worst case time complexity (time taken to explore all the possibilities if none is found or if it is the last one).
As for the optimizations there can be 2 types of improvements:
Implementation improvements
You're calculating x-2, x-1, x+1, x+2 and the same for y at least the double of the times.
I can suggest to rewrite things like this:
int sm1 = size - 1;
int xm2 = x - 2;
int yp1 = y + 1;
if((xm2 >= 0) && (yp1 <= (sm1))){
mark(arr[x][y]);
if(backtrack(xm2, yp1))
return true;
else
unmark(arr[x][y]);
}
int ym1 = y-1;
if((xm2 >= 0) && (ym1 >= 0)){
mark(arr[x][y]);
if(backtrack(xm2, ym1))
return true;
else
unmark(arr[x][y]);
}
note the reusing of precalculated values also in subsequent blocks.
I've found this to be more effective than what I was especting; meaning that variable assignment and recall is faster than doing the operation again.
Also consider saving sm1 = s - 1; and area = s * s; in the constructor instead of calculating each time.
However this (being an implementation improvement and not an algorithm improvement) will not change the time complexity order but only divide the time by a certain factor.
I mean time complexity O(8^(n^2)) = k*8^(n^2) and the difference will be in a lower k factor.
Algorithm improvements
I can think this:
for each tour starting on in a cell in the diagonals (like starting in (0,0) as in your example) you can consider only the first moves being on one of the two half checkboards created by the diagonal.
This is beacouse of the simmetry or it exists 2 simmetric solutions or none.
This gives O(4*8^(n^2-2)) for that cases but the same remains for non simmetric ones.
Note that again O(4*8^(n^2-2)) = O(8^(n^2))
try to interrupt the rush early if some global condition suggests that a solution is impossible given the current markings.
for example the horse cannot jump two bulk columns or rows so if you have two bulk marked columns (or rows) and unmarked cells on both sides you're sure that there will be no solution. Consider that this can be checked in O(n) if you mantain number of marked cells per col/row updated. Then if you check this after each marking you're adding O(n*8^(n^2)) time that is not bad if n < = 8. Workaround is simply not to check alwais but maybe every n/8 markings (checking counter % 8 == 4 for example or better counter > 2*n && counter % 8 == 4
find other ideas to cleverly interrupt the search early but remember that the backtrack algorithm with 8 options will always have its nature of being O(8^(2^n)).
Bye
Here is my 2 cents. I started with the basic backtracking algorithm. It was waiting indefinitely for n > 7 as you mentioned. I implemented warnsdorff rule and it works like a magic and gives result in less than a second for boards of sizes till n = 31. For n >31, it was giving stackoverflow error as recursion depth exceeded the limit. I could find a better discussion here which talks about problems with warnsdorff rule and possible further optimizations.
Just for the reference, I am providing my python implementation of Knight's Tour problem with warnsdorff optimization
def isValidMove(grid, x, y):
maxL = len(grid)-1
if x maxL or y maxL or grid[x][y] > -1 :
return False
return True
def getValidMoves(grid, x, y, validMoves):
return [ (i,j) for i,j in validMoves if isValidMove(grid, x+i, y+j) ]
def movesSortedbyNumNextValidMoves(grid, x, y, legalMoves):
nextValidMoves = [ (i,j) for i,j in getValidMoves(grid,x,y,legalMoves) ]
# find the number of valid moves for each of the possible valid mode from x,y
withNumNextValidMoves = [ (len(getValidMoves(grid,x+i,y+j,legalMoves)),i,j) for i,j in nextValidMoves]
# sort based on the number so that the one with smallest number of valid moves comes on the top
return [ (t[1],t[2]) for t in sorted(withNumNextValidMoves) ]
def _solveKnightsTour(grid, x, y, num, legalMoves):
if num == pow(len(grid),2):
return True
for i,j in movesSortedbyNumNextValidMoves(grid,x,y,legalMoves):
#For testing the advantage of warnsdorff heuristics, comment the above line and uncomment the below line
#for i,j in getValidMoves(grid,x,y,legalMoves):
xN,yN = x+i,y+j
if isValidMove(grid,xN,yN):
grid[xN][yN] = num
if _solveKnightsTour(grid, xN, yN, num+1, legalMoves):
return True
grid[xN][yN] = -2
return False
def solveKnightsTour(gridSize, startX=0, startY=0):
legalMoves = [(2,1),(2,-1),(-2,1),(-2,-1),(1,2),(1,-2),(-1,2),(-1,-2)]
#Initializing the grid
grid = [ x[:] for x in [[-1]*gridSize]*gridSize ]
grid[startX][startY] = 0
if _solveKnightsTour(grid,startX,startY,1,legalMoves):
for row in grid:
print ' '.join(str(e) for e in row)
else:
print 'Could not solve the problem..'
Examine your algorithm. At each depth of recursion, you examine each of 8 possible moves, checking which are on the board, and then recursively process that position. What mathematical formula best describes this expansion?
You have a fixed board size, int[8][8], maybe you should make it dynamic,
class horse
{
...
int** board; //[s][s];
...
};
horse::horse(int s)
{
int i, j;
size = s;
board = (int**)malloc(sizeof(int*)*size);
for(i = 0; i < size; i++)
{
board[i] = (int*)malloc(sizeof(int)*size);
for(j = 0; j < size; j++)
{
board[i][j] = 0;
}
}
}
Changing your tests a little by adding a function to check that a board move is legal,
bool canmove(int mx, int my)
{
if( (mx>=0) && (mx<size) && (my>=0) && (my<size) ) return true;
return false;
}
Note that the mark() and unmark() are very repetitive, you really only need to mark() the board, check all legal moves, then unmark() the location if none of the backtrack() return true,
And rewriting the function makes everything a bit clearer,
bool horse::backtrack(int x, int y)
{
if(counter > (size * size))
return true;
if(unvisited(board[x][y]))
{
mark(board[x][y]);
if( canmove(x-2,y+1) )
{
if(backtrack(x-2, y+1)) return true;
}
if( canmove(x-2,y-1) )
{
if(backtrack(x-2, y-1)) return true;
}
if( canmove(x-1,y+2) )
{
if(backtrack(x-1, y+2)) return true;
}
if( canmove(x-1,y-2) )
{
if(backtrack(x-1, y-2)) return true;
}
if( canmove(x+2,y+1) )
{
if(backtrack(x+2, y+1)) return true;
}
if( canmove(x+2,y-1) )
{
if(backtrack(x+2, y-1)) return true;
}
if( canmove(x+1,y+2) )
{
if(backtrack(x+1, y+2)) return true;
}
if( canmove(x+1,y-2) )
{
if(backtrack(x+1, y-2)) return true;
}
unmark(board[x][y]);
}
return false;
}
Now, think about how deep the recursion must be to visit every [x][y]? Fairly deep, huh?
So, you might want to think about a strategy that would be more efficient. Adding these two printouts to the board display should show you how many backtrack steps occured,
int counter = 1; int stepcount=0;
...
void horse::print()
{
cout<< "counter: "<<counter<<endl;
cout<< "stepcount: "<<stepcount<<endl;
...
bool horse::backtrack(int x, int y)
{
stepcount++;
...
Here is the costs for 5x5, 6x6, 7x6,
./knightstour 5
>>> Successful! <<<
counter: 26
stepcount: 253283
./knightstour 6
>>> Successful! <<<
counter: 37
stepcount: 126229019
./knightstour 7
>>> Successful! <<<
counter: 50
stepcount: 56342
Why did it take fewer steps for 7 than 5? Think about the ordering of the moves in the backtrack - if you change the order, would the steps change? What if you made a list of the possible moves [ {1,2},{-1,2},{1,-2},{-1,-2},{2,1},{2,1},{2,1},{2,1} ], and processed them in a different order? We can make reordering the moves easier,
int moves[ ] =
{ -2,+1, -2,-1, -1,+2, -1,-2, +2,+1, +2,-1, +1,+2, +1,-2 };
...
for(int mdx=0;mdx<8*2;mdx+=2)
{
if( canmove(x+moves[mdx],y+moves[mdx+1]) )
{
if(backtrack(x+moves[mdx], y+moves[mdx+1])) return true;
}
}
Changing the original move sequence to this one, and running for 7x7 gives different result,
{ +2,+1, +2,-1, +1,+2, +1,-2, -2,+1, -2,-1, -1,+2, -1,-2 };
./knightstour 7
>>> Successful! <<<
counter: 50
stepcount: -556153603 //sheesh, overflow!
But your original question was,
The question is: What is the Time complexity for this algorithm and how can I optimize it?!
The backtracking algorithm is approximately 8^(n^2), though it may find the answer after as few as n^2 moves. I'll let you convert that to O() complexity metric.
I think this guides you to the answer, without telling you the answer.
this is a new solution:
in this method, using the deadlock probability prediction at the next movement of the knight in the chessboard, a movement will be chose that it’s tending to the deadlock probability is less than the other ones, we know at the first step this deadlock probability is zero for every cells and it will be changed gradually. The knight in the chessboard has between 2 and 8 moves, so each cells has predetermined value for next move.
Selecting the cells that have less available movement is best choice because it will tend to the deadlock in the future unless it is filled. There is an inverse relationship between allowed movement number and reach an impasse.
the outer cells is in the highest priority, As regards in a knight's tour problem the knight has to cross a cell only once, these value will be changed gradually in future travels.
Then in the next step a cell will be chose that has these conditions
The number of its adjacent empty cells is less than others, or in the other words the probability to be filled is more
After selecting, the adjacent houses doesn’t going to deadlock
you can read my full article about this problem here
Knight tour problem article
and you can find the full source from here
Full Source in GitHub
I hope it will be useful