'Error in solution to a problem of matrix of "o's" and "x's" in C language. In this we need to count and identify adjacent elements
Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.
Input The first line contains an integer n (1 ≤ n ≤ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.
Output Print "YES" or "NO" (without the quotes) depending on the answer to the problem.
I have been pondering quite a while as to what I have done wrong, can someone please help me point out the error in my logic in my code.
#include<stdio.h>
int main () {
int n,flag=0;
scanf("%d",&n);
char arr[n][n];
int arr_counter[n][n];
for (int x=0;x<n;x++) {
for (int y=0;y<n;y++) {
arr_counter[x][y] = 0;
}
}
for (int i=0;i<n;i++) {
for (int j=0;j<n;j++) {
scanf("%c",&arr[i][j]);
}
}
// corners
// top left
if(arr[1][0]=='o') {
arr_counter[0][0] += 1;
}
if(arr[0][1] == 'o') {
arr_counter[0][0] += 1;
}
// top right
if(arr[0][n-2]=='o') {
arr_counter[0][n-1] += 1;
}
if(arr[1][n-1] == 'o') {
arr_counter[0][n-1] += 1;
}
// bottom left
if(arr[n-2][0]=='o') {
arr_counter[n-1][0] += 1;
}
if(arr[n-1][1] == 'o') {
arr_counter[n-1][0] += 1;
}
// bottom right
if(arr[n-2][n-1]=='o') {
arr_counter[n-1][n-1] += 1;
}
if(arr[n-1][n-2] == 'o') {
arr_counter[n-1][n-1] += 1;
}
// edges
for (int a=1;a<n;a++) {
if(arr[0][a+1] == 'o') {
arr_counter[0][a] += 1;
}
if(arr[0][a-1] == 'o') {
arr_counter[0][a] += 1;
}
if(arr[1][a] == 'o') {
arr_counter[0][a] += 1;
}
}
for (int b=1;b<n;b++) {
if(arr[b-1][0] == 'o') {
arr_counter[b][0] += 1;
}
if(arr[b+1][0] == 'o') {
arr_counter[b][0] += 1;
}
if(arr[b][1] == 'o') {
arr_counter[b][0] += 1;
}
}
for (int c=1;c<n;c++) {
if(arr[c-1][n-1] == 'o') {
arr_counter[c][n-1] += 1;
}
if(arr[c+1][n-1] == 'o') {
arr_counter[c][n-1] += 1;
}
if(arr[c][n-2] == 'o') {
arr_counter[c][n-1] += 1;
}
}
for (int d=1;d<n;d++) {
if(arr[n-1][d+1] == 'o') {
arr_counter[n-1][d] += 1;
}
if(arr[n-1][d-1] == 'o') {
arr_counter[n-1][d] += 1;
}
if(arr[n-2][d] == 'o') {
arr_counter[n-1][d] += 1;
}
}
//middle
for (int s=1;s<n-1;s++) {
for (int t=1;t<n-1;t++) {
if(arr[s+1][t] == 'o') {
arr_counter[s][t] += 1;
}
if(arr[s-1][t] == 'o') {
arr_counter[s][t] += 1;
}
if(arr[s][t+1] == 'o') {
arr_counter[s][t] += 1;
}
if(arr[s][t-1] == 'o') {
arr_counter[s][t] += 1;
}
}
}
for (int k=0;k<n;k++) {
for (int l=0;l<n;l++) {
if (arr_counter[k][l]%2 != 0) {
flag = 1;
}
}
}
if (flag == 0) {
printf("YES");
} else if (flag == 1) {
printf("NO");
}
}
/*
Test Case 1
input
3
xxo
xox
oxx
output
YES
Test Case 2
input
4
xxxo
xoxo
oxox
xxxx
output
NO
*/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
