Please help me with this code. I don't know why is it not printing the output. The code is based on Warnsdorff’s algorithm for Knight’s tour problem. It says "[Error]:Id returned 1 exit status. When I executed it online it sait runtime error. Please help to optimize my code.
#include <bits/stdc++.h>
#define n 8
using namespace std;
static int x_move[n] = {2, 2, -1, -1, 1, 1, -2, -2};
static int y_move[n] = {1, -1, 2, -2, 2, -2, 1, -1};
void print(int arr[][n]) {
for (int i = 0 ; i < n ; ++i) {
for (int j = 0 ; j < n ; ++j)
cout<<arr[i][j]<<" ";
cout<<"\n";
}
}
bool safe(int arr[][n] , int r , int c) {
return (r >= 0 && c >= 0 && r < n && c < n && arr[r][c] == -1);
}
bool neighbour(int r , int c , int sr , int sc) {
for (int i = 0 ; i < n ; ++i)
if ((r + x_move[i] == sr) && (c + x_move[i] == sc))
return true;
return false;
}
int depth(int arr[][n] , int r , int c) {
int co = 0;
for (int i = 0 ; i < n ; ++i)
if (safe(arr , r + x_move[i] , c + y_move[i]))
c++;
return c;
}
bool next_one(int arr[][n] , int *r , int *c) {
int nr , nc;
int min_dep_index = -1;
int min_dep = n + 1;
int k;
int s = rand() % n;
for (int co = 0 ; co < n ; ++co) {
int i = (s + co) % n;
nr = *r + x_move[i];
nc = *c + y_move[i];
k = depth(arr , nr , nc);
if (safe(arr , *r , *c) && k < min_dep) {
min_dep_index = i;
min_dep = k;
}
}
if (min_dep_index == -1)
return false;
nr = *r + x_move[min_dep_index];
nc = *c + y_move[min_dep_index];
arr[nr][nc] = arr[*r][*c] + 1;
*r = nr;
*c = nc;
return true;
}
bool foo(int arr[][n]) {
for (int i = 0 ; i < n ; ++i)
for (int j = 0 ; j < n ; ++j)
arr[i][j] = -1;
int r , c , sr , sc;
sc = rand() % n;
sr = rand() % n;
r = sr;
c = sc;
arr[r][c] = 1;
for (int i = 0 ; i < n*n ; ++i) {
if (next_one(arr , &r , &c) == false)
return false;
}
if (!neighbour(r , c , sr , sc))
return false;
print(arr);
return true;
}
int main() {
int arr[n][n];
srand(time(nullptr));
while (foo(arr) == false) {
;
}
return 0;
}
Related
I've read many posts but I can't figure out where is my error so I go with it.
My program throws the segfault at the cout<<endl. When I erase it, the program doesn't even print anything. It just prints the segfault. Aparently the program never reach to sort the vector.
#include <iostream>
#include <vector>
using namesapce std
void inserctionSort(std::vector<double> &v, int i, int j)
{
double temp;
for(i; i < v.size(); i++)
{
temp = v[i];
j = i - 1;
while((v[j] > temp) && (j >= 0))
{
v[j+1] = v[j];
j--;
}
v[j+1] = temp;
}
}
void merge_(std::vector<double> &v, int i, int k, int j)
{
std::vector<double> w(v.size());
int n = j - i + 1;
int p = i;
int q = k + 1;
for(int l = 0; l < n; l++)
{
if(p <= k && (q > j || v[p] <= v[q]))
{
w[l] = v[p];
p++;
}else
{
w[l] = v[q];
q++;
}
}
for(int l = 0; l < n; l++)
v[i - 1 + l] = w[l];
}
void mergeSort(std::vector<double> &v, int i, int j)
{
int n = j - i + 1, n0 = 3;
int k;
if(n <= n0)
{
inserctionSort(v,i,j);
}else
{
k = i - 1 + n / 2;
mergeSort(v, i, k);
mergeSort(v, k + 1, j);
merge_(v, i, k, j);
}
}
int main()
{
vector<double> v1 = {3.2,4.1,55.42,2.24,5.424,667.32,35.54};
cout<<"Vector desordenado: ";
for(int i = 0; i < v1.size(); i++)
cout<<v1[i]<<", ";
cout<<"hola";
cout<<endl;
cout<<"hola";
mergeSort(v1, 0, v1.size()-1); //--> Core generado
//quickSort(v1, 0, v1.size()-1);
cout<<"Vector ordenado: ";
for(int i = 0; i < v1.size(); i++)
cout<<v1[i]<<", ";
return 0;
}
You have problems in your code with vector indices assuming value -1 inside a couple of loops.
I have corrected these mistakes below, a working version of your code:
#include <iostream>
#include <vector>
using namespace std;
void inserctionSort(vector<double> &v, int i, int j)
{
int v_size = v.size();
double temp;
for (; i < v_size; i++) {
temp = v[i];
j = i - 1;
while ( (j >= 0) && (v[j] > temp) ) { // swapped conditions, as when j=-1, v[j]>temp is undefined
v[j+1] = v[j];
j--;
}
v[j+1] = temp;
}
}
void merge_(vector<double> &v, int i, int k, int j)
{
vector<double> w( v.size() );
int n = j - i + 1;
int p = i;
int q = k + 1;
for (int l = 0; l < n; l++) {
if ( p <= k && (q > j || v[p] <= v[q]) ) {
w[l] = v[p];
p++;
} else {
w[l] = v[q];
q++;
}
}
for(int l = 0; l < n; l++)
v[i + l] = w[l]; // deleted -1 from v[i - 1 + l], as it leads to v[-1] for i,l = 0
}
void mergeSort(vector<double> &v, int i, int j)
{
int n = j - i + 1, n0 = 3; // n = v.size()
int k;
if (n <= n0) {
inserctionSort(v,i,j);
} else {
k = i - 1 + n / 2;
mergeSort(v, i, k);
mergeSort(v, k + 1, j);
merge_(v, i, k, j);
}
}
int main()
{
vector<double> v1 = {3.2,4.1,55.42,2.24,5.424,667.32,35.54};
cout<<"Vector desordenado: ";
for (unsigned i = 0; i < v1.size(); i++)
cout<<v1[i]<<", ";
cout << "hola";
cout << endl;
cout << "hola";
mergeSort(v1, 0, v1.size()-1); //--> Core generado
//quickSort(v1, 0, v1.size()-1);
cout<<"Vector ordenado: ";
for (unsigned i = 0; i < v1.size(); i++)
cout << v1[i] << ", ";
return 0;
}
I have a problem with deallocating a 3 dimensional vector in c++, I get the error "CTR detected that the application wrote to memory after end of heap buffer".
Can somebody tell me what I am doing wrong? Thank you in advance.
Allocation:
count = new int**[w];
for (int i = 0; i < w; ++i)
{
count[i] = new int*[h];
for (int j = 0; j < h; ++j)
{
count[i][j] = new int[120];
for (int k = 20; k < 120; ++k)
{
count[i][j][k] = 0;
}
}
}
Deallocation:
for (int i = 0; i < w; ++i)
{
for (int j = 0; j < h; ++j)
{
delete [] count[i][j];
}
delete [] count[i];
}
delete [] count;
count = NULL;
This is my entire code:
#include <filesystem>
#include <stdexcept>
#include "pch.h"
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <math.h>
using namespace std;
using namespace cv;
class cerc {
int raza;
int a;
int b;
public:
cerc()
{
a = 0;
b = 0;
raza = 0;
}
inline cerc(int raza, int a, int b)
{
this->a = a;
this->b = b;
this->raza = raza;
}
inline cerc(cerc& c)
{
a = c.a;
b = c.b;
raza = c.raza;
}
void print()
{
std::cout << " (" << (int)this->a << ", " << (int)this->b << ", " << (int)this->raza << ") ";
}
inline bool operator==(const cerc& other) const
{
if (this->a == other.a && this->b == other.b && this->raza == other.raza)
return true;
else return false;
}
inline bool egal(int raza, int a, int b) const
{
if (this->a == a && this->b == b && this->raza == raza)
return true;
else return false;
}
inline void copy(cerc &c2)
{
this->raza = c2.raza;
this->a = c2.a;
this->b = c2.b;
}
inline void copy(int raza, int a, int b)
{
this->a = a;
this->raza = raza;
this->b = b;
}
const int getA()
{
return a;
}
const int getB()
{
return b;
}
const int getRaza()
{
return raza;
}
};
int min(int a, int b)
{
if (a < b)
return a;
return b;
}
void createVector(int*** count, Mat img, int w, int h)
{
int a = 0;
int b = 0;
int r = 0;
int wminus = 5 * (w / 6);
int hminus = 5 * (h / 6);
int wstart = w / 6;
int hstart = h / 6;
int x, y;
for (x = wstart; x < wminus; x++)
for (y = hstart; y < hminus; y++)
{
if (((Scalar)(img.at<uchar>(Point(x, y)))).val[0] == 255)
{
for (a = wstart; a < wminus; a += 1)
for (b = hstart; b < hminus; b += 1)
{
r = (int)sqrt((b - y)*(b - y) + (a - x)*(a - x));
if (r >= 20 && r <= 120)
count[a][b][r]++;
}
}
}
}
void cercFinal(cerc &cercMax, int***count, int w, int h)
{
int wminus = 5 * (w / 6);
int hminus = 5 * (h / 6);
int wstart = w / 6;
int hstart = h / 6;
int maxNr = count[0][0][0];
for (int i = wstart; i < wminus; i += 1)
for (int j = hstart; j < hminus; j += 1)
for (int k = 20; k < 60; k++)
if (maxNr < count[i][j][k])
{
maxNr = count[i][j][k];
cercMax.copy(k, i, j);
}
cout << maxNr;
}
void cercFinalSecund(cerc &SecondCircle, cerc &FirstCircle, int***count, int w, int h)
{
int wminus = 3 * (w / 4);
int hminus = 3 * (h / 4);
int wstart = w / 4;
int hstart = h / 4;
int minIrisRay = (int)(FirstCircle.getRaza() * 1.5);
int maxIrisRay = FirstCircle.getRaza() * 4;
int maxNr = count[0][0][0];
for (int i = wstart; i < wminus; i += 1)
for (int j = hstart; j < hminus; j += 1)
for (int k = 40; k < 120; k++)
{
if (k >= minIrisRay && k <= maxIrisRay)
{
if (maxNr < count[i][j][k] && !(cerc(k, i, j) == FirstCircle) && abs(j - FirstCircle.getB()) < 2 && abs(i - FirstCircle.getA()) < 2)
{
maxNr = count[i][j][k];
SecondCircle.copy(k, i, j);
}
}
}
}
int main()
{
Mat imgCanny;
Mat imgBlur;
int ***count;
for (int i = 10; i < 50; i++)
{
Mat_<uchar> img = imread("C://Users//Maria//Downloads//CASIA-IrisV2//CASIA-IrisV2//device1//00" + std::to_string(i) + "//00" + std::to_string(i) + "_000.bmp", IMREAD_GRAYSCALE);
//img.convertTo(img, -1, 4, 0);
//int t = img.at<uchar>(1, 2).val[0];
int w = img.size().width;
int h = img.size().height;
medianBlur(img, imgBlur, 15);
//GaussianBlur(img, imgBlur, Size(8, 8), 0);
Canny(imgBlur, imgCanny, 30, 40);
//imshow("canny", imgCanny);
int m = min(w, h);
count = new int**[w];
for (int i = 0; i < w; ++i)
{
count[i] = new int*[h];
for (int j = 0; j < h; ++j)
{
count[i][j] = new int[120];
for (int k = 20; k < 120; ++k)
{
count[i][j][k] = 0;
}
}
}
createVector(count, imgCanny, w, h);
cerc final(0, 0, 0);
cerc finalSecund(0, 0, 0);
cercFinal(final, count, w, h);
cercFinalSecund(finalSecund, final, count, w, h);
cout << endl << "cerc=";
final.print();
Point p(final.getA(), final.getB());
Mat imgColor = imread("C://Users//Maria//Downloads//CASIA-IrisV2//CASIA-IrisV2//device1//00" + std::to_string(i) + "//00" + std::to_string(i) + "_000.bmp", IMREAD_COLOR);
circle(imgColor, p, final.getRaza(), Scalar(255, 0, 0), 4, 8, 0);
Point ps(finalSecund.getA(), finalSecund.getB());
cout << endl << "cerc=";
finalSecund.print();
circle(imgColor, ps, finalSecund.getRaza(), Scalar(255, 0, 0), 4, 8, 0);
imshow("iris", imgColor);
for (int i = 0; i < w; ++i)
{
for (int j = 0; j < h; ++j)
{
delete [] count[i][j];
}
delete [] count[i];
}
delete [] count;
count = NULL;
waitKey(0);
}
return 0;
}
If I delete the line count[a][b][r]++; the deallocation works fine. Is anything wrong with this statement?
so I was doing this code in which you scan a number then that number pairs of numerical strings example
5
5 5
6 6
7 7
8 8
and the program should then output
25
36
49
64
81
which is the first number *the second number
but mine outputs
25
61 //25+36
110 //110+49
174 //110+64
the reason is that in my code I keep each multiplication in an array called arr2 which I declared globally and since I don't reset all values back to 0 it keeps adding up but the problem is don't know how to reset all of its values back to 0 since when I tried it would not let me
code in which I did not try to reset the array which works the way I already mentioned
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<long long> vi;
typedef pair<long long, long long> pi;
typedef vector<pi> vpi;
#define FOR(i, a, b) for (ll i = ll(a); i < ll(b); i++)
#define ROF(i, a, b) for (ll i = ll(a); i >= ll(b); i--)
#define f first
#define s second
#define pb emplace_back
#define mp make_pair
#define SQ(a) (a) * (a)
#define all(a) (a).begin(), (a).end()
int arr[9999];
int multiply(string a, string b, int n)
{
int r = 0, j = 0;
int x = int(b[0] - 48);
for (int i = n - 1; i >= 0; i--) {
int mult = 0, y = int(a[i] - 48);
mult = x * y + r;
arr[j] = mult % 10;
r = (mult - mult % 10) / 10;
j++;
}
if (r != 0) {
arr[j] = r;
return n + 1;
}
else {
return n;
}
}
int arr2[9999] = { 0 }, u = 0; //here I declared it
int suma(int w, int f)
{
int b[w];
int r = 0;
int s = 0, j = 0;
w = w + f;
for (int i = f; i < w; i++) {
s = arr2[i] + arr[i - f] + r;
arr2[i] = s % 10;
r = (s - s % 10) / 10;
j++;
}
if (r != 0) {
if (w >= u) {
arr2[j] = r;
j++;
}
else {
while (r != 0) {
s = arr2[j] + arr[j - f] + r;
arr2[j] = s % 10;
r = (s - s % 10) / 10;
j++;
}
}
}
int u = max({ w, u, j });
return u;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int as;
cin >> as;
for (int cfg = 0; cfg < as; cfg++) {
int w, k = 0, l = 0;
string a, b, c;
cin >> a >> b;
reverse(b.begin(), b.end());
for (int i = 0; i < b.length(); i++) {
c = b[i];
w = multiply(a, c, a.length());
k = suma(w, i);
l = max(k, l);
}
int narr[l];
narr[l] = { 0 };
copy(arr2 + 0, arr2 + l, narr);
int n = sizeof(narr) / sizeof(narr[0]);
reverse(narr, narr + n);
int qw = 0;
for (int i = 0; i < l; i++) {
if (narr[i] != 0) {
qw = 1;
}
if (qw == 1) {
cout << narr[i];
}
}
cout << endl;
}
return 0;
}
Code in which I tried but gives me an error:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<long long> vi;
typedef pair<long long, long long> pi;
typedef vector<pi> vpi;
#define FOR(i, a, b) for (ll i = ll(a); i < ll(b); i++)
#define ROF(i, a, b) for (ll i = ll(a); i >= ll(b); i--)
#define f first
#define s second
#define pb emplace_back
#define mp make_pair
#define SQ(a) (a) * (a)
#define all(a) (a).begin(), (a).end()
int arr[9999];
int multiply(string a, string b, int n)
{
int r = 0, j = 0;
int x = int(b[0] - 48);
for (int i = n - 1; i >= 0; i--) {
int mult = 0, y = int(a[i] - 48);
mult = x * y + r;
arr[j] = mult % 10;
r = (mult - mult % 10) / 10;
j++;
}
if (r != 0) {
arr[j] = r;
return n + 1;
}
else {
return n;
}
}
int arr2[9999] = { 0 }, u = 0; //here I declared it
int suma(int w, int f)
{
int b[w];
int r = 0;
int s = 0, j = 0;
w = w + f;
for (int i = f; i < w; i++) {
s = arr2[i] + arr[i - f] + r;
arr2[i] = s % 10;
r = (s - s % 10) / 10;
j++;
}
if (r != 0) {
if (w >= u) {
arr2[j] = r;
j++;
}
else {
while (r != 0) {
s = arr2[j] + arr[j - f] + r;
arr2[j] = s % 10;
r = (s - s % 10) / 10;
j++;
}
}
}
int u = max({ w, u, j });
return u;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int as;
cin >> as;
for (int cfg = 0; cfg < as; cfg++) {
arr2[9999] = { 0 }; //here I try to set all the values back to 0
int w, k = 0, l = 0;
string a, b, c;
cin >> a >> b;
reverse(b.begin(), b.end());
for (int i = 0; i < b.length(); i++) {
c = b[i];
w = multiply(a, c, a.length());
k = suma(w, i);
l = max(k, l);
}
int narr[l];
narr[l] = { 0 };
copy(arr2 + 0, arr2 + l, narr);
int n = sizeof(narr) / sizeof(narr[0]);
reverse(narr, narr + n);
int qw = 0;
for (int i = 0; i < l; i++) {
if (narr[i] != 0) {
qw = 1;
}
if (qw == 1) {
cout << narr[i];
}
}
cout << endl;
}
return 0;
}
Format!Style:
C++ online code formatter © 2014 by KrzaQ
Powered by vibe.d, the D language and clang-format
So the question would be if is there any way to reset all the values to 0 or any other way to solve the problem if you can you could submit a code that works if not just tell me how to fix it,thank you
To clear the arr array, you can use memset like:
memset(arr, 0, sizeof arr);
I made a similar post on here but didn't get any feedback. The problem came from here.
I am trying to simply print out the entries of the longest increasing matrix. I thought I had it figure out when I tried the following matrix:
2 2 1
1 2 1
2 2 1
I got an output of:
1
2
Then when I increased n , m = 4. I got this matrix:
2 2 1 1
2 1 2 2
1 2 2 3
1 2 1 3
And this output for the paths entries:
1
1
2
When it should be just:
1
2
3
Here is my code:
#include <algorithm>
#include <cmath>
#include <list>
#include <vector>
#include <stdio.h>
#include <random>
#include <utility>
#include <iostream>
void printPath(std::vector<int> &numPaths) {
std::sort(numPaths.begin(), numPaths.end());
for(int i = 0; i < numPaths.size(); i++) {
std::cout << numPaths[i] << std::endl;
}
}
int DFS(int i, int j, const std::vector<std::vector<int> > &matrix, std::vector<std::vector<int> > &length) {
std::vector<std::pair<int,int> > dics{{-1,0},{1,0},{0,-1},{0,1}}; // used to check the directions left, right, up, down
std::vector<int> path;
if(length[i][j] == -1) {
int len = 0;
for(auto p: dics) {
int x = i + p.first, y = j + p.second;
if(x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size()) continue; // Check to make sure index is not out of boundary
if(matrix[x][y] > matrix[i][j]) { // compare number
len = std::max(len, DFS(x,y,matrix,length));
}
}
length[i][j] = len + 1;
}
return length[i][j];
}
int longestPath(std::vector<std::vector<int> > matrix) {
int n = matrix[0].size();
if (n == 0) {
return 0;
}
int m = matrix.size();
if (m == 0) {
return 0;
}
std::vector<std::vector<int> > length(m, std::vector<int>(n,-1));
std::vector<int> numPaths;
int len = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int newLen = DFS(i,j,matrix,length);
if(newLen > len) {
numPaths.push_back(matrix[i][j]);
}
len = std::max(len, DFS(i, j, matrix, length));
}
}
printPath(numPaths);
return len;
}
int main() {
// Specify the number of rows and columns of the matrix
int n = 4;
int m = 4;
// Declare random number generator
std::mt19937 gen(10);
std::uniform_int_distribution<> dis(1, 3);
// Fill matrix
std::vector<std::vector<int> > matrix;
for(int i = 0; i < m; i++) {
std::vector<int> row;
for(int j = 0; j < n; j++) {
row.push_back(0);
}
matrix.push_back(row);
}
// Apply random number generator to create matrix
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
matrix[i][j] = dis(gen);
}
}
// Print matrix to see contents
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
//std::vector<std::vector<int> > mat = {{1,2,3}};
int result = longestPath(matrix);
std::cout << "The longest path is " << result << std::endl;
}
I would really appreciate if someone can tell me where I am going wrong.
#include <algorithm>
#include <cmath>
#include <vector>
#include <stdio.h>
#include <random>
#include <utility>
#include <iostream>
#define MATRIX_SIZE 1000
void printPath(std::vector<int> &numPaths) {
std::sort(numPaths.begin(), numPaths.end());
for(int i = 0; i < numPaths.size(); i++) {
std::cout << numPaths[i] << std::endl;
}
}
int DFS(int i, int j, const std::vector<std::vector<int> > &matrix, std::vector<std::vector<int> > &length) {
std::vector<std::pair<int,int> > dics{{-1,0},{1,0},{0,-1},{0,1}}; // used to check the directions left, right, up, down
std::vector<int> path;
if(length[i][j] == -1) {
int len = 0;
for(auto p: dics) {
int x = i + p.first, y = j + p.second;
if(x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size()) continue; // Check to make sure index is not out of boundary
if(matrix[x][y] > matrix[i][j]) { // compare number
len = std::max(len, DFS(x,y,matrix,length));
}
}
length[i][j] = len + 1;
}
return length[i][j];
}
void printMatrix(std::vector<std::vector<int>> &matrix) {
for (int i =0; i < matrix.size(); i++) {
for (int j =0; j < matrix[0].size(); j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
}
std::vector<int> generatePath(int i, int j, const std::vector<std::vector<int>> &matrix, const std::vector<std::vector<int>> &length) {
int max_length = length[i][j];
std::vector<int> path(max_length, 0);
for (int current_length = max_length; current_length >= 1; current_length--) {
std::vector<std::pair<int,int> > dics{{-1,0},{1,0},{0,-1},{0,1}}; // used to check the directions left, right, up, down
int index = max_length - current_length;
for (auto p: dics) {
path[index] = matrix[i][j];
int x = i + p.first, y = j + p.second;
if(x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size()) continue;
if (current_length - length[x][y] == 1) {
i = x;
j = y;
break;
}
}
}
printPath(path);
return path;
}
int longestPath(std::vector<std::vector<int> > matrix) {
int n = matrix[0].size();
if (n == 0) {
return 0;
}
int m = matrix.size();
if (m == 0) {
return 0;
}
std::vector<std::vector<int> > length(m, std::vector<int>(n,-1));
std::vector<int> numPaths;
int len = 0;
int maxRow = 0;
int maxCol = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int currentLength = DFS(i, j, matrix, length);
if (currentLength > len) {
len = currentLength;
maxRow = i;
maxCol = j;
}
}
}
generatePath(maxRow, maxCol, matrix,length);
return len;
}
int main(int argc, char *argv[]) {
std::mt19937 gen(10);
std::uniform_int_distribution<> dis(1, 1000000);
// Fill matrix
std::vector<std::vector<int> > matrix;
for(int i = 0; i < MATRIX_SIZE; i++) {
std::vector<int> row;
for(int j = 0; j < MATRIX_SIZE; j++) {
row.push_back(0);
}
matrix.push_back(row);
}
// Apply random number generator to create matrix
for(int i = 0; i < MATRIX_SIZE; i++) {
for(int j = 0; j < MATRIX_SIZE; j++) {
matrix[i][j] = dis(gen);
}
}
// Print matrix
//printMatrix(matrix);
timespec start, end;
clock_gettime(CLOCK_REALTIME, &start);
printf("the longest path is %d\n", longestPath(matrix));
clock_gettime(CLOCK_REALTIME, &end);
printf("found in %ld micros\n", (end.tv_sec * 1000000 + end.tv_nsec / 1000) - (start.tv_sec * 1000000 + start.tv_nsec / 1000));
return 0;
}
# Print the Longest Increasing Path in a Matrix #
class Solution:
# Possible directions allowed from the given question.
DIRECTIONS = [[1, 0], [-1, 0], [0, 1], [0, -1]]
def longestIncreasingPath(self, matrix):
# From the given question:
# ----- m = rows ----- i
# ----- n = cols ----- j
m = len(matrix)
if m == 0:
return 0
n = len(matrix[0])
if n == 0:
return 0
cache = [[0] * n for _ in range(m)]
longestPath = 0
maximum = 1
for i in range(m):
for j in range(n):
longestPath = self.depthFirstSearch(matrix, i, j, m, n, cache)
maximum = max(maximum, longestPath)
return (cache, maximum)
def depthFirstSearch(self, matrix, i, j, m, n, cache):
if cache[i][j] != 0:
return cache[i][j]
maxPath = 1
for direction in self.DIRECTIONS:
x = direction[0] + i
y = direction[1] + j
if x < 0 or y < 0 or x >= m or y >= n or matrix[x][y] <= matrix[i][j]:
continue
length = 1 + self.depthFirstSearch(matrix, x, y, m, n, cache)
maxPath = max(maxPath, length)
cache[i][j] = maxPath # Save the value at i, j for future usage.
return maxPath
def printPath(self, matrix):
# Check if longestPath is 0.
if not self.longestIncreasingPath(matrix):
return None
length = self.longestIncreasingPath(matrix)[1]
cache = self.longestIncreasingPath(matrix)[0]
# From the given question:
# ----- m = rows ----- i
# ----- n = cols ----- j
m = len(cache)
n = len(cache[0])
location = []
# Traverse the cache to obtain the location of the starting point of the longest increasing path in the matrix.
# Time complexity, T(n) = O(n*m) ----- if not a square matrix.
for i in range(m):
for j in range(n):
if cache[i][j] == length:
location.extend([i, j])
i, j = location[0], location[1]
result = [matrix[i][j]] # The result container is initialised with the element of the matrix at the obtained position
# Time complexity, T(n) = O(4n) ----- where n = length of longest increasing path in the given matrix and the 4 being the length of the DIRECTIONS matrix.
for _ in range(length):
for direction in self.DIRECTIONS:
x = direction[0] + i
y = direction[1] + j
if x < 0 or y < 0 or x >= m or y >= n or cache[i][j] - 1 != cache[x][y]:
continue
result.append(matrix[x][y])
i = x
j = y
return result
I'm trying to develop a wordsearch which finds the word "OIE" (indicating how many times appears), based in an integer unidimensional array that saves the directions (8), but I get strange errors when I run this (and incorrect outputs).
This is the code:
int arrf[8] = {0, -1, -1, -1, 0, 1, 1, 1};
int arrc[8] = {-1, -1, 0, 1, 1, 1, 0,-1};
char s[] = "OIE";
int main() {
int n, m;
while (cin >> n >> m) {
int res = 0;
vector<vector<char> > S(n, vector<char>(m));
for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) cin >> S[i][j];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
for (int d = 0; d < 8; ++d) {
bool trobat = true;
for (int h = 0; h < 3 and trobat; ++h) {
int f = i + arrf[d], c = j + arrc[d];
if (f < 0 || f >= n || c < 0 || c >= m || S[f][c] != s[h])
trobat = false;
}
if (trobat) res++;
}
}
}
cout << res << endl;
}
}
Could somebody help me to fix this? I would appreciate.
Regards.
One error is that this line
int f = i + arrf[d], c = j + arrc[d];
should be
int f = i + h*arrf[d], c = j + h*arrc[d];
With your code it doesn't matter how many times you go round the inner loop you are still checking the same position.