My c++ program runs, but say "8queens.exe has stopped working" - c++

this code attempts to solve the 4 queens problem, placing 4 queens on a 4*4 chessboard without any of them being able to capture eachother
#include <iostream>
using namespace std;
int Place(int Chess[][4], int collumn, int i);
bool Check(int Chess[][4], int collumn, int i);
int findrow(int Chess[][4], int collumn);
const int size = 3;
int main()
{
int Chess[4][4];
int collumn;
int i = 0;
collumn = 0;
for(int s = 0; s < 4; s++)
{
for(int j = 0; j < 4; j ++)
{
Chess[s][j] = 0;
}
}
//Chess[0][0] = 1;
//Chess[3][3] = 1;
//if(Check(Chess, 3, 3) == false)
Place(Chess, collumn, i);
for(int z = 0; z < 4; z++)
{
for(int a = 0; a < 4; a++)
{
if(Chess[z][a] == 1)
cout<<"Row: "<<z<<"Collumn: "<<a<<"."<<endl;
}
cout<<endl;
}
system("pause");
return 0;
}
int Place(int Chess[][4], int collumn, int i)
{
if(collumn > size)
return 0;
while(i <= size)
{
if(Check(Chess, collumn, i) == true)
{
//cout<<"hi"<<endl;
Chess[collumn][i] = 1;
return(Place(Chess, (collumn + 1), i));
}
i ++;
}
if(i>= size)
{
//cout<<"hilo"<<endl;
return Place(Chess, collumn-1, findrow(Chess, collumn-1));
}
}
bool Check(int Chess[][4], int collumn, int i)//checks to see if it can be captured
{// very inneficitnt
int x = collumn;// this is so we can now work in terms of x and y
int y = i;
bool found = true;
// checks all the diagonal captures
if(Chess[x -1 ][y -1]== 1&& x>=1 && y >=1 )
found = false;
if(Chess[x -2 ][y - 2]== 1&& x>=2 && y>=2 )
found = false;
if(Chess[x - 3][y - 3]== 1 && x>=3 && y>=3 )
found = false;
if(Chess[x + 1][y - 1] == 1&& x<=2 && y>=1 )
found = false;
if(Chess[x + 2][y -2] == 1&& x<=1 && y>=2)
found = false;
if(Chess[x + 3][y - 3] == 1 && x<=0 && y>=3)
found = false;
if(Chess[x + 1][y + 1] == 1 && x<=2 && y<=2)
found = false;
if(Chess[x + 2][y + 2] == 1&& x<=1 && y<=1)
found = false;
if(Chess[x + 3][y + 3] == 1 && x<=0 && y<=0 )
found = false;
if(Chess[x -1 ][y + 1]== 1 && x>=1 && y<=2 )
found = false;
if(Chess[x - 2][y + 2] == 1&& x>=2 && y<=1 )
found = false;
if(Chess[x - 3][y + 3] == 1&& x>=3 && y<=0)
found = false;
//checks all the horizontal captures. We don't need to check for vertical captures
if(Chess[x + 1][y] == 1 && x<=2)
found = false;
if(Chess[x + 2][y] == 1&& x<=1 )
found = false;
if(Chess[x+3][y] == 1 && x<=0)
found = false;
if(Chess[x -1 ][y] == 1&& x>=1)
found = false;
if(Chess[x-2][y] == 1&& x>=2 )
found = false;
if(Chess[x-3][y] == 1 && x>=3)
found = false;
if(found == false)
return false;
if(found == true)
return true;
}
int findrow(int Chess[][4], int collumn)
{
for(int z = 0; z < 4; z++)
{
if(Chess[collumn][z] == 1)
{
Chess[collumn][z] = 0;
return z;
}
}
}

The first thing I see is a probable out-of-bounds access:
if(Chess[x -1 ][y -1]== 1&& x>=1 && y >=1 )
What if the value of x is 0? You are accessing Chess[-1][y], which is out of bounds. Your if statement does not stop this, even with the x>=1 condition.
The if will first test the Chess[x-1][y-1]==1 condition. If you want this to not happen, place the test for x>=1 before Chess[x-1][y-1]==1.
But even with this, that entire section of code looks suspicious. I wouldn't be surprised if there were more out-of-bounds accesses.

Related

g++ : array bound is not an integer constant before ‘]’ token

I'm having trouble with g++ producing this error code when I try to compile my code:
maze.h:16:29: error: array bound is not an integer constant before ‘]’ token
bool canMove(int m[mazeSize][mazeSize], int r, int c);
Now, I have already done some research into this error and it seems to be causes by the array size not being known at compile time. I have tried making the array constant, but that ends up causing more errors later on as the array is reassigned later on in the code and produces this error:
maze.cpp: In member function ‘int Maze::startMazeGen()’:
maze.cpp:185:15: error: assignment of read-only location ‘maze[i][j]’
maze[i][j] = 1;
^
I have also seen people mention that it would just be easier to work with vectors instead, but I'm also having issues with trying to repurpose the code to work with vectors instead of arrays.
Here's the rest of my code:
movement.h
#pragma once
#include <iostream>
#include <curses.h>
#ifndef MOVEMENT_H
#define MOVEMENT_H
class Movement
{
public:
static const int playerX = 2; // sets player starting position
static const int playerY = 2;
};
#endif
movement.cpp
#include <iostream>
#include <curses.h>
#include <ctime>
#include "maze.h"
//#include "movement.h"
bool running = true;
int playerX = 2;
int playerY = 2;
//Maze::maze Maze::mazeGen;
//int Maze::mazeGen.Maze::maze::generateMaze::maze(int m[Maze::mazeSize]
[Maze::mazeSize], int r, int c);
// Detect Char input
// and move player in direction
void getUserInput()
{
char userInput = getch();
if (userInput == 'w') {
int playerY2 = playerY - 1;
if (Maze::maze[playerY2][playerX] == ' ') {
Maze::maze[playerY][playerX] = ' ';
playerY--;
Maze::maze[playerY][playerX] = 'x';
}
}
if (userInput == 'a') {
int playerX2 = playerX - 1;
if (Maze::maze[playerY][playerX2] == ' ') {
Maze::maze[playerY][playerX] = ' ';
playerX--;
Maze::maze[playerY][playerX] = 'x';
}
}
if (userInput == 's') {
int playerY2 = playerY + 1;
if (Maze::maze[playerY2][playerX] == ' ') {
Maze::maze[playerY][playerX] = ' ';
playerY++;
Maze::maze[playerY][playerX] = 'x';
}
}
if (userInput == 'd') {
int playerX2 = playerX + 1;
if (Maze::maze[playerY][playerX2] == ' ') {
Maze::maze[playerY][playerX] = ' ';
playerX++;
Maze::maze[playerY][playerX] = 'x';
}
}
}
// Main game update
// Runs through all functions required
void update()
{
getUserInput();
clear();
Maze::generateMaze;
refresh();
}
//
//
/*int main()
{
// Initate nCurses display
initscr();
while (true) {
update();
}
// End nCurses display
endwin();
return 0;
}*/
maze.h
#pragma once
// MAZE.h
#include <iostream>
#include <ctime>
#ifndef MAZE_H
#define MAZE_H
extern int r;
extern int c;
extern int mazeSize; //number can be changed to make some big sweaty mazes making it an even number makes it act a bit weird sometimes so its better to use an odd number
extern int maze[mazeSize][mazeSize];
class Maze
{
public:
int blockedSquare = 1;
void move(int m[mazeSize][mazeSize], int &r, int &c);
bool canMove(int m[mazeSize][mazeSize], int r, int c);
void solve(int m[mazeSize][mazeSize], int &r, int &c);
bool canSolve(int m[mazeSize][mazeSize], int r, int c);
void generateMaze(int m[mazeSize][mazeSize], int r, int c);
int findStart();
void printMaze(int m[mazeSize][mazeSize]);
int startMazeGen();
};
#endif
maze.cpp
#include <iostream>
#include <ctime>
#include <vector>
#include "maze.h"
bool foundExit = false;
int mazeSize = 31;
int maze[mazeSize][mazeSize] = { 0 };
void Maze::generateMaze(int const m[mazeSize][mazeSize], int r, int c)
{
bool made = false;
while (made == false)
{
if (c == mazeSize - 1)
foundExit = true;
if (canSolve(m, r, c))
{
solve(m, r, c);
}
else if (canMove(m, r, c))
{
m[r][c] = 2; //2 means you can't move from that square, setting any lower stops maze from being made
move(m, r, c); //move to first open space that can be found
}
else
made = true;
}
}
void Maze::move(int m[mazeSize][mazeSize], int &r, int &c)
{
if (m[r][c + 1] == 0)
c++;
else if (m[r + 1][c] == 0)
r++;
else if (m[r][c - 1] == 0)
c--;
else if (m[r - 1][c] == 0)
r--;
else
generateMaze(maze, r, c); //if maze cant be solved it generates a new one so the player doesnt have something that is impossible to solve
}
bool Maze::canMove(int m[mazeSize][mazeSize], int r, int c) //if there is an adjacent zero space, return true
{
if (m[r][c + 1] == 0)
return true;
else if (m[r + 1][c] == 0)
return true;
else if (m[r][c - 1] == 0)
return true;
else if (m[r - 1][c] == 0)
return true;
else
return false;
}
void Maze::solve(int m[mazeSize][mazeSize], int &r, int &c) //solves maze through with dijkstras algorithmto ensure it can be solved
{
bool foundSolution = false;
while (foundSolution == false)
{
int direction = (1 + rand() % 4) * 3;
switch (direction)
{
case 3:
if (c + 1 <= mazeSize - 1 && m[r][c + 2] == blockedSquare && m[r - 1][c + 1] == blockedSquare && m[r + 1][c + 1] == blockedSquare && m[r][c + 1] == blockedSquare)
{
if (c == mazeSize - 2 && foundExit == true)
; //do nothing
else
{
c++;
foundSolution = true;
}
}
break;
case 6:
if (r + 1 <= mazeSize - 2 && m[r + 2][c] == blockedSquare && m[r + 1][c + 1] == blockedSquare && m[r + 1][c - 1] == blockedSquare && m[r + 1][c] == blockedSquare && c != 0 && c != mazeSize - 1)
{
r++;
foundSolution = true;
}
break;
case 9:
if (c - 1 >= 0 && m[r][c - 2] == blockedSquare && m[r - 1][c - 1] == blockedSquare && m[r + 1][c - 1] == blockedSquare && m[r][c - 1] == blockedSquare && c - 1 != 0)
{
c--;
foundSolution = true;
}
break;
case 12:
if (r - 1 >= 1 && m[r - 2][c] == blockedSquare && m[r - 1][c + 1] == blockedSquare && m[r - 1][c - 1] == blockedSquare && m[r - 1][c] == blockedSquare && c != 0 && c != mazeSize - 1)
{
r--;
foundSolution = true;
}
break;
}
}
m[r][c] = 0;
}
bool Maze::canSolve(int m[mazeSize][mazeSize], int r, int c) //if an adjacent square can be moved to, return true
{
bool solvable = false;
if (r <= mazeSize - 3 && m[r + 2][c] == blockedSquare && m[r + 1][c + 1] == blockedSquare && m[r + 1][c - 1] == blockedSquare && m[r + 1][c] == blockedSquare && c != 0 && c != mazeSize - 1) //if adjacent space can be moved to
{
solvable = true;
}
else if (c <= mazeSize - 2 && m[r][c + 2] == blockedSquare && m[r - 1][c + 1] == blockedSquare && m[r + 1][c + 1] == blockedSquare && m[r][c + 1] == blockedSquare)
{
if (c == mazeSize - 2 && foundExit == true)
; //do nothing
else
{
solvable = true;
}
}
else if (r >= 2 && m[r - 2][c] == blockedSquare && m[r - 1][c + 1] == blockedSquare && m[r - 1][c - 1] == blockedSquare && m[r - 1][c] == blockedSquare && c != 0 && c != mazeSize - 1) //if not on extreme left or right
{
solvable = true;
}
else if (c >= 1 && m[r][c - 2] == blockedSquare && m[r - 1][c - 1] == blockedSquare && m[r + 1][c - 1] == blockedSquare && m[r][c - 1] == blockedSquare && c - 1 != 0)
{
solvable = true;
}
return solvable;
}
int Maze::findStart()
{
return 1 + rand() % (mazeSize - 2);
}
void Maze::printMaze(int m[mazeSize][mazeSize])
{
std::cout << std::endl;
for (int i = 0; i < mazeSize; ++i) {
for (int j = 0; j < mazeSize; ++j)
{
switch (m[i][j])
{
case 0:
std::cout << " ";
break;
case 1:
std::cout << "▓▓";
break;
case 2:
std::cout << " ";
break;
case 3:
std::cout << " ";
break;
}
}
std::cout << std::endl;
}
}
int Maze::startMazeGen()
{
srand(time(0));
for (int i = 0; i < mazeSize; ++i)
for (int j = 0; j < mazeSize; ++j)
maze[i][j] = 1;
int r = findStart();
//int r = 0;
int c = 0;
maze[r][c] = 0;
generateMaze(maze, r, c);
maze[r][c] = 2;
printMaze(maze);
std::cout << "Press enter to continue ...";
std::cin.get();
}
The purpose of this code is to randomly generate a maze, solve it, and then print it to the screen if it can be solved. If the maze can't be solved, it keeps generating a new one until it can be solved.I aim to make this work with the movement code so that the user can navigate the maze.
Any help is appreciated on this issue. Thank you!
"Now, I have already done some research into this error and it seems to be causes by the array size not being known at compile time. I have tried making the array constant, but that ends up causing more errors later on as the array is reassigned later on in the code"
You're conflating two things here, the array and the array size.
The array size should be a a compile-time constant. Since you're assigning to the array, the array elements shouldn't be const at all.
const int arrSize = 3;
int arr[arrSize][arrSize];

A function about checking whether the game is over in 2048 game

I took some days to code 2048 game. And now I made most of the functions but one, testing whether the game is over. To code this game, my idea is to merge the same numbers first with the function up(down, left or right)_merge and make all the numbers go to the arrow direction that user presses with the function all_go_up(down, left or right). And then add a new number with the add_new_number function.
Here are some piece of those code I mentioned above:
void up_merge()
{
for(int i = 1; i < 4; i++) {
for(int j = 0; j < 4; j++) {
if(grid[i][j] > 0 && grid[i - 1][j] == grid[i][j]) {
while(grid[i - 1][j] == grid[i][j]) {
grid[i - 1][j] *= 2;
grid[i][j] = 0;
}
}
else if(grid[i][j] > 0 && grid[i - 1][j] == 0 && grid[i - 2][j] == grid[i][j]) {
while(grid[i - 2][j] == grid[i][j]) {
grid[i - 2][j] *= 2;
grid[i][j] = 0;
}
}
else if(grid[i][j] > 0 && grid[i - 1][j] == 0 && grid[i - 2][j] == 0 && grid[i - 3][j] == grid[i][j]) {
while(grid[i - 3][j] == grid[i][j]) {
grid[i - 3][j] *= 2;
grid[i][j] = 0;
}
}
}
}
}
void all_go_up()
{
for(int i = 3; i > 0; i--) {
for(int j = 0; j < 4; j++) {
if(grid[i][j] > 0 && grid[i - 1][j] == 0) {
grid[i - 1][j] = grid[i][j];
grid[i][j] = 0;
}
for(int k = 3; k > 0; k--) {
if(grid[k][j] > 0 && grid[k - 1][j] == 0) {
grid[k - 1][j] = grid[k][j];
grid[k][j] = 0;
}
}
}
}
}
bool add_new_number(int num)
{
int n = rand() % 2 + 1;
int newnumber = 1 << n;
int r, c;
switch(num) {
case 1: //up
r = rand() % 2 + 2;
c = rand() % 4;
break;
case 2: //down
r = rand() % 2;
c = rand() % 4;
break;
case 3: //left
r = rand() % 4;
c = rand() % 2 + 2;
break;
case 4: //right
r = rand() % 4;
c = rand() % 2;
break;
}
do {
if(check_empty() == 1) {
if(grid[r][c] == 0) {
grid[r][c] = newnumber;
return false;
}
if(grid[r][c] != 0) {
switch(num) {
case 1: //up
r = rand() % 2 + 2;
c = rand() % 4;
break;
case 2: //down
r = rand() % 2;
c = rand() % 4;
break;
case 3: //left
r = rand() % 4;
c = rand() % 2 + 2;
break;
case 4: //right
r = rand() % 4;
c = rand() % 2;
break;
}
}
}
else {
return false;
}
} while(true);
}
I have some other functions to check whether the grid is full and so on. I also tried use some while() and for() to do this, too. But I do not know where I get wrong to code the function to test whether the game is over.
I hope I express my problem well. Hoping to get some suggestions to code the test_fail function without changing too much of my code. Thanks.
With all the respect, your code looks totally unreadable. Consider functional approach where you compose few smaller function to break down more complex problem. I am going to demonstrate this in Typescript but it would be very similar in C++. In this way the code is I believe self-explanatory.
type Board = number[][]
function isGameOver(board: Board) {
if (hasEmptySpace(board)) return false
return checkHorizontalGameOver(board) && checkVerticalGameOver(board)
}
function hasEmptySpace(board: Board) {
for (let r = 0; r < NUM_ROWS; r++) {
for (let c = 0; c < NUM_COLS; c++) {
if (board[r][c] === 0) return true
}
}
return false
}
function checkHorizontalGameOver(board: Board) {
for (let i = 0; i < NUM_ROWS; i++) {
for (let j = 0; j < NUM_COLS - 1; j++) {
if (board[i][j] === board[i][j + 1]) return false
}
}
return true
}
function checkVerticalGameOver(board: Board) {
for (let i = 0; i < NUM_ROWS - 1; i++) {
for (let j = 0; j < NUM_COLS; j++) {
if (board[i][j] === board[i + 1][j]) return false
}
}
return true
}
I understand it's 5 years ago as I am reading now and your skills in programming are far far better, but still - I will post it here for people who might come across this so it can possibly help them.

Segmentation fault in recursive backtracking maze generator C++

I am trying to create a maze generator using recursive backtracking and have come across a problem that I just can't get my head around. For some reason my move function is returning the value "18446744073709551615". This is (of course) leading to a segmentation fault. Why is my move function returning such a large value when my move function can only increase or decrease the value by 2?
bool maze::generate(size_t x, size_t y) {
//mark the position as visited
labyrinth.s[y][x] = true;
//print to see progress
//this->print();
//if the position is not out of bounds
if (x < 0 || x > labyrinth.MAXWIDTH - 1 || y < 0 || y > labyrinth.MAXHIGHT - 1) {
//if the position is the endpoint return true
if (labyrinth.v[y][x - 1] == 'W' || labyrinth.v[y][x + 1] == 'W' || labyrinth.v[y - 1][x] == 'W' || labyrinth.v[y + 1][x] == 'W') {
return true;
}
}
//pick a random direction
do {
d = size_t(rand() % 4);
} while(!this->pos_test(x, y, d));
std::cout << x << ' ' << y << std::endl;
if (d == UP) {
y = move(x, y, UP);
}
else if (d == DOWN) {
y = move(x, y, DOWN);
}
else if (d == RIGHT) {
x = move(x, y, RIGHT);
}
else if (d == LEFT) {
x = move(x, y, LEFT);
}
else{
}
std::cout << x << ' ' << y << std::endl;
//recursively generate the maze
if (this->generate(x, y)) {
return true;
}
}
void maze::initialize(size_t x, size_t y) {
//set the maxhight and the maxwidth to y and x
labyrinth.MAXHIGHT = y;
labyrinth.MAXWIDTH = x;
//set all elements in the vector to #
for (size_t i = 0; i < labyrinth.MAXHIGHT; i++) {
std::vector<char> temp;
for (size_t j = 0; j < labyrinth.MAXWIDTH; j++) {
temp.push_back(labyrinth.wall);
}
labyrinth.v.push_back(temp);
}
for (size_t i = 0; i < labyrinth.MAXHIGHT; i++) {
for (size_t j = 0; j < labyrinth.MAXWIDTH; j++) {
if (j % 2 == 1 && i % 2 == 1 && j != labyrinth.MAXWIDTH - 1 && j != 0 && i != labyrinth.MAXHIGHT - 1 && i != 0) {
labyrinth.v[j][i] = labyrinth.path;
}
}
}
//set all posistions to unvisited
for (size_t i = 0; i < labyrinth.MAXHIGHT; i++) {
std::vector<bool> temp2;
for (size_t j = 0; j < labyrinth.MAXWIDTH; j++) {
temp2.push_back(false);
}
labyrinth.s.push_back(temp2);
}
//setup the start point
labyrinth.v[0][1] = 'S';
//setup the endpoint
labyrinth.v[labyrinth.MAXHIGHT - 2][labyrinth.MAXWIDTH - 1] = 'W';
}
//if a position has been visited or if not possible to go to return true
bool maze::pos_test(size_t x, size_t y, size_t d) const {
//if the position is out of bounds return false
if (x < 0 || y < 0 || x > labyrinth.MAXWIDTH - 1 || y > labyrinth.MAXHIGHT - 1) {
return true;
}
else if (x == 1 && d == LEFT) {
return true;
}
else if (y == 1 && d == UP) {
return true;
}
else if (x == labyrinth.MAXWIDTH - 1 && d == RIGHT) {
return true;
}
else if (y == labyrinth.MAXHIGHT - 1 && d == DOWN) {
return true;
}
else if (d == UP) {
return labyrinth.s[y - 2][x];
}
else if (d == DOWN) {
return labyrinth.s[y + 2][x];
}
else if (d == RIGHT) {
return labyrinth.s[y][x + 2];
}
else if (d == LEFT) {
return labyrinth.s[y][x - 2];
}
else {
return true;
}
}
size_t maze::move(size_t x, size_t y, size_t d) {
//if the position is out of bounds return without modifying
if (x < 0 || x > labyrinth.MAXWIDTH - 1) {
return x;
}
else if (y < 0 || y > labyrinth.MAXHIGHT - 1) {
return y;
}
else if (d == UP) {
labyrinth.v[y - 1][x] = labyrinth.path;
return y = y - 2;
}
else if (d == DOWN) {
labyrinth.v[y + 1][x] = labyrinth.path;
return y = y + 2;
}
else if (d == RIGHT) {
labyrinth.v[y][x + 1] = labyrinth.path;
return x = x + 2;
}
else if (d == LEFT) {
labyrinth.v[y][x - 1] = labyrinth.path;
return x = x - 2;
}
else {
}
}
You are underflowing your unsigned 64-bit return type size_t.
You are checking whether x and y are below zero, but that's not enough, because 0 and 1 will still be too low because you are subtracting 2!
The number you get is 0xFFFFFFFFFFFFFFFF in hexadecimal. This is the highest possible value for an unsigned 64-bit integer.
It comes from calculating 1 - 2. Yes, this is supposed to be -1, but because your move function doesn't return a signed number but an unsigned one (check the docs on size_t), it can't be negative! Instead, it wraps around to the highest possible number.
You can imagine this in the same way you would get ...99999999999 when you try to calculate 1 - 2 on paper ignoring the "you can't subtract a higher number from a smaller one on paper" rule.
As a side note: I guess the negative result is undesired anyway, because actually your huge number, once added to a pointer, will in turn overflow back into positive, so basically it will work the same is a real -1 in your case and the segmentation fault comes from accessing something right before the beginning of your buffer, not far beyond it, but it comes down to the same thing.
Apart from that, there is no need to do return y = y - 2 and such. Just return y - 2.

Coin Change Bottom Up Dynamic Programming

http://uva.onlinejudge.org/external/6/674.html I'm trying to solve that problem. Note, though, that it's not the minimum coin change problem, it asks me for the different number of ways to make N cents using 50, 25, 15, 10, 5 and 1 cent coins. It's fairly straightforward, so I made this function:
int count(int n, int m) // n is the N of the problem, m is the number of coin types and s[] is {1, 5, 10, 25, 50}
{
if (n == 0)
{
return 1;
}
if (n < 0)
{
return 0;
}
if (m < 0 && n >= 1)
{
return 0;
}
return DP[n][m - 1] + DP[n - s[m]][m];
}
Fairly straightforward too is adding Dynamic Programming with memoization:
int count(int n, int m)
{
if (n == 0)
{
return 1;
}
if (n < 0)
{
return 0;
}
if (m < 0 && n >= 1)
{
return 0;
}
if (DP[n][m - 1] == -1 || DP[n - s[m]][m] == -1)
{
return count(n, m - 1) + count(n - s[m], m);
}
else
{
return DP[n][m - 1] + DP[n - s[m]][m];
}
}
However, none of these is fast enough - I need bottom up Dynamic Programming, but I am having difficulties coding it, even with some help from Algorithmist - http://www.algorithmist.com/index.php/Coin_Change.
void generate()
{
for (i = 0; i < MAX; i++)
{
for (u = 0; u < m; u++)
{
if (i == 0)
{
DP[i][u] = 1;
}
else if (u == 0)
{
DP[i][u] = 0;
}
else if (s[u] > i)
{
DP[i][u] = DP[i][u - 1];
}
else
{
DP[i][u] = DP[i][u - 1] + DP[i - s[u]][u];
}
}
}
}
I get 0 for every result for some reason, here's my full code:
#include <stdio.h>
#include <string.h>
using namespace std;
#define MAX 7490
int s[] = {1, 5, 10, 25, 50}, m = 5, input, DP[MAX][5], i, u;
int count(int n, int m)
{
if (n == 0)
{
return 1;
}
if (n < 0)
{
return 0;
}
if (m < 0 && n >= 1)
{
return 0;
}
if (DP[n][m - 1] == -1 || DP[n - s[m]][m] == -1)
{
return count(n, m - 1) + count(n - s[m], m);
}
else
{
return DP[n][m - 1] + DP[n - s[m]][m];
}
}
void generate()
{
for (i = 0; i < MAX; i++)
{
for (u = 0; u < m; u++)
{
if (i == 0)
{
DP[i][u] = 1;
}
else if (u == 0)
{
DP[i][u] = 0;
}
else if (s[u] > i)
{
DP[i][u] = DP[i][u - 1];
}
else
{
DP[i][u] = DP[i][u - 1] + DP[i - s[u]][u];
}
}
}
}
int main()
{
memset(DP, -1, sizeof DP);
generate();
while (scanf("%d", &input) != EOF)
{
//printf("%d\n", count(input, 4));
printf("%d\n", DP[input][4]);
}
return 0;
}
You did the mistake here:
else if (u == 0)
{
DP[i][u] = 0;
}
It should be DP[i][u]=1 because you can produce any value i using 1 cent coin in 1 possible way. i.e. to take 5 cent you will take 5 one cent coins which is one way to make 5-cent in total.
-----
Btw, in you 1st approach in count method did you have this:
if (DP[n][m - 1] == -1 || DP[n - s[m]][m] == -1)
{
return count(n, m - 1) + count(n - s[m], m);
}
Or this:
if (DP[n][m - 1] == -1 || DP[n - s[m]][m] == -1)
{
return DP[n][m] = count(n, m - 1) + count(n - s[m], m);
}
If you did not memoize an already calculated result then this memoization check if (DP[n][m - 1] == -1 || DP[n - s[m]][m] == -1) will never work, which might be the cause of your 1st approach to be too slow :-?

runtime error on uva's minesweeper

I have written a program to solve uva's minesweeper problem (10189) in C++.
I have written the code, and it seems to work correctly on my machine. Unfortunately my submission seems to be giving me run-time error (uva does not mention the error message or reason in such cases). I am pasting the code here:
using namespace std;
void nullCheck(void *ptr)
{
exit(0);
}
typedef unsigned int uint;
class Field
{
public:
vector <vector<uint> > nghBombCnt; //neighbourBombCount
vector <vector<bool> > isBomb;
uint width;
uint height;
public:
Field(uint w, uint h)
{
}
Field() { }
~Field()
{
}
};
int main(void)
{
vector<Field> fieldList;
do
{
Field curField;
uint width, height;
scanf("%u %u", &height, &width);
curField.width = width;
curField.height = height;
for (uint rowCtr = 0; rowCtr < curField.height; rowCtr++)
{
vector<bool> curBombRow;
for (uint colCtr = 0; colCtr < curField.width; colCtr++)
{
char curSymb;
scanf("%1s", &curSymb);
switch (curSymb)
{
case '.':
curBombRow.push_back(false); break;
case '*':
curBombRow.push_back(true); break;
default: break;
}
}
curField.isBomb.push_back(curBombRow);
}
if (!(curField.width == 0 && curField.height == 0))
fieldList.push_back(curField);
else
break;
} while (1);
for (uint fieldCtr = 0; fieldCtr < fieldList.size(); fieldCtr++)
{
Field curField = fieldList.at(fieldCtr);
for (uint rowCtr = 0; rowCtr < curField.height; rowCtr++)
{
vector<uint> curRow;
for (uint colCtr = 0; colCtr < curField.width; colCtr++)
{
uint bombCnt = 0;
if (curField.isBomb[rowCtr][colCtr])
{
curRow.push_back(0);
continue;
}
if (colCtr != 0 && curField.isBomb[rowCtr][colCtr - 1])
bombCnt++; //east
if (rowCtr != 0 && curField.isBomb[rowCtr - 1][colCtr])
bombCnt++; //north
if (rowCtr != curField.height - 1
&& curField.isBomb[rowCtr + 1][colCtr])
bombCnt++; //south
if (colCtr != curField.width - 1
&& curField.isBomb[rowCtr][colCtr + 1])
bombCnt++; //west
if (colCtr != curField.width - 1 && rowCtr != 0
&& curField.isBomb[rowCtr -1][colCtr + 1])
bombCnt++; //north-east
if (colCtr != 0 && rowCtr != curField.height - 1
&& curField.isBomb[rowCtr + 1][colCtr - 1])
bombCnt++; // south-west
if (colCtr != curField.width - 1
&& rowCtr != curField.height - 1
&& curField.isBomb[rowCtr + 1][colCtr + 1])
bombCnt++; //south-east
if (colCtr != 0 && rowCtr != 0
&& curField.isBomb[rowCtr - 1][colCtr - 1])
bombCnt++; //north-west
curRow.push_back(bombCnt);
}
curField.nghBombCnt.push_back(curRow);
}
fieldList[fieldCtr] = curField;
}
for (uint fieldNo = 0; fieldNo < fieldList.size(); fieldNo++)
{
printf("Field #%u:\n", fieldNo + 1);
Field curField = fieldList.at(fieldNo);
for (uint rowCtr = 0; rowCtr < curField.height; rowCtr++)
{
for (uint colCtr = 0; colCtr < curField.width; colCtr++)
{
if (curField.isBomb[rowCtr][colCtr])
printf("*");
else
printf("%u", curField.nghBombCnt[rowCtr][colCtr]);
}
printf("\n");
}
printf("\n");
}
return 0;
}