×

# Algorithm that searches a value in an 2 dimensional array (matrix).

 4 Searching a value in an 2 dimensional array (matrix). asked 10 Nov '16, 09:46 2★rashedcs 497●6●17●55 accept rate: 4%

# include <iterator>

int main() { const size_t N = 3; int a[N][N] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

int value = 9;

auto it = std::find( reinterpret_cast<int *>( a ),
reinterpret_cast<int *>( a ) + N * N,
value );

if ( it != reinterpret_cast<int *>( a ) + N * N )
{
size_t n = std::distance( reinterpret_cast<int *>( a ),
it );
std::cout << "Row = " << n / N << ", Column = " << n % N << std::endl;
}

size_t row = 0;
size_t col = 0;

for ( ; row < N; row++ )
{
col = 0;
while ( col < N && a[row][col] != value ) col++;
if ( col != N ) break;
}

if ( row != N )
{
std::cout << "Row = " << row << ", Column = " << col << std::endl;
}

return 0;


}

26
accept rate: 100%

 2 I think it is good tutorial for solving this problem. answered 10 Nov '16, 11:13 2★rashedcs 497●6●17●55 accept rate: 4%
 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×846

question asked: 10 Nov '16, 09:46

question was seen: 542 times

last updated: 10 Nov '16, 11:13