Two Dimensional Arrays

Slides:



Advertisements
Similar presentations
COSC2007 Data Structures II
Advertisements

By Michael Coco. Setting up the board  Two dimensional array board[x][y]  First column second row is 10  Walls will be labeled with 2  Open positions.
A backtrack data structure and algorithm
Announcements Assignment #4 is due tonight. Last lab program is going to be assigned this Wednesday. ◦ A backtracking problem.
Eight queens puzzle. The eight queens puzzle is the problem of placing eight chess queens on an 8×8 chessboard such that none of them are able to capture.
Chapter 7 Multidimensional Arrays. Defining a two dimensional array elementType[][] arrayName; // Java pro elementType arrayName[][]; // C++ alternate.
Backtracking COP Backtracking  Backtracking is a technique used to solve problems with a large search space, by systematically trying and eliminating.
Engineering Problem Solving with C++ An Object Based Approach Chapter 7 Two-Dimensional Arrays and Matrices.
Backtracking What is backtracking?
1 ICS103 Programming in C Lecture 16: 2-Dimensional Arrays.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 8 Multidimensional.
Backtracking.
Programming Arrays. Question Write a program that reads 3 numbers from the user and print them in ascending order. How many variables do we need to store.
Data Structures Using C++ 2E Chapter 6 Recursion.
Search Much of AI has traditionally revolved around search –Search means “searching among all the possibilities for an answer” (or possibly the best answer)
Copyright © 2011 Pearson Education, Inc. Publishing as Prentice Hall.
CSE 221/ICT221 Analysis and Design of Algorithms Lecture 06: CSE 221/ICT221 Analysis and Design of Algorithms Lecture 06: Analysis of Algorithm using List,
Data Structures Using C++ 2E Chapter 6 Recursion.
Recursion Chapter 5.
Announcements.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Arrays Arrays are objects that help us organize large amounts of information.
Matrices Jordi Cortadella Department of Computer Science.
A.Abhari CPS1251 Multidimensional Arrays Multidimensional array is the array with two or more dimensions. For example: char box [3] [3] defines a two-dimensional.
Recursion. Recursive Methods HAVE: 1.A base case or termination condition that causes the method to end 2.A non-base case whose actions move the algorithm.
8.1 Matrices & Systems of Equations
Recursion: Backtracking
CSE 143 Lecture 17 More Recursive Backtracking reading: "Appendix R" on course web site slides created by Marty Stepp and Hélène Martin
Back Tracking Project Due August 11, 1999 N-queens: –A classic puzzle for chess buffs is the N- Queens problem. Simply stated: is it possible to place.
HISTORY The problem was originally proposed in 1848 by the chess player Max Bezzel, and over the years, many mathematicians, including Gauss have worked.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
CSE 143 Lecture 17 More Recursive Backtracking reading: "Appendix R" on course web site slides created by Marty Stepp and Hélène Martin
Solving N-Queens in Clojure
Two dimensional arrays in Java Computer Science 3 Gerb Objective: Use matrices in Java.
“Planning is bringing the future into the present so that you can do something about it now.” – Alan Lakein Thought for the Day.
Announcements This Wednesday, Class and Labs are cancelled! The last lab is due this Wednesday … how many people are planning on doing it? Finally posted.
Data Structures Using C++ 2E1 Recursion and Backtracking: DFS Depth first search (a way to traverse a tree or graph) Backtracking can be regarded as a.
Sudoku Jordi Cortadella Department of Computer Science.
Two Dimensional Arrays. Two-dimensional Arrays Declaration: int matrix[4][11]; 4 x 11 rows columns
Matrices Matrices A matrix (say MAY-trix) is a rectan- gular array of objects (usually numbers). An m  n (“m by n”) matrix has exactly m horizontal.
Module #9: Matrices Rosen 5 th ed., §2.7 Now we are moving on to matrices, section 7.
1 Data Structures CSCI 132, Spring 2014 Lecture 17 Backtracking.
The "8 Queens" problem Consider the problem of trying to place 8 queens on a chess board such that no queen can attack another queen. What are the "choices"?
CS 100Lecture 191 CS100J Lecture 19 n Previous Lecture –Two dimensional arrays. –Reasonable size problem (a past assignment). –Stepwise refinement. –Use.
Introduction to Programming (in C++) Multi-dimensional vectors Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
1 Arrays of Arrays An array can represent a collection of any type of object - including other arrays! The world is filled with examples Monthly magazine:
CSE 143 Lecture 18 More Recursive Backtracking slides created by Marty Stepp
© 2006 Pearson Addison-Wesley. All rights reserved 6-1 Chapter 6 Recursion as a Problem- Solving Technique.
Programming for Art: Arrays – 2D ART 315 Dr. J. R. Parker Art/Digital Media Lab Lec 16 Fall 2010.
Two-Dimensional Data Class of 5 students Each student has 3 test scores Store this information in a two- dimensional array First dimension: which student.
CSE 143 read: 12.5 Lecture 18: recursive backtracking.
Data Structures & Algorithms Lecturers : Boontee Kruatrachue Room no. 913 Kritawan Siriboon Room no. 913 Lecturers : Boontee Kruatrachue Room no. 913 Kritawan.
Data Structures & Algorithms Lecturer : Kritawan Siriboon, Room no. 913 Text : Data Structures & Algorithm Analysis in C, C++,… Mark Allen Weiss, Addison.
1 Tirgul 11: Recursion & Backtracking. 2 Elements of a recursive solution (Reminder) A base case that is so simple we need no computation to solve it.
Programming application CC213
Intro to Computer Science II
Data Structures and Algorithms
Fundamentals of Programming II Backtracking with Stacks
Sit-In Lab 1 Ob-CHESS-ion
The "8 Queens" problem Consider the problem of trying to place 8 queens on a chess board such that no queen can attack another queen. What are the "choices"?
CSE 143 Lecture 19 More Recursive Backtracking
Jordi Cortadella Department of Computer Science
adapted from Recursive Backtracking by Mike Scott, UT Austin
Ch. 6 Recursion as a Problem Solving Technique
CS Software Studio Assignment 1
Exercise: Dice roll sum
CSE 143 Lecture 18 More Recursive Backtracking
Matrix Addition, C = A + B Add corresponding elements of each matrix to form elements of result matrix. Given elements of A as ai,j and elements of B as.
The "8 Queens" problem Consider the problem of trying to place 8 queens on a chess board such that no queen can attack another queen. What are the "choices"?
Announcements Assignment #4 is due tonight. Last lab program is going to be assigned this Wednesday. ◦ A backtracking problem.
Presentation transcript:

Two Dimensional Arrays

Two-dimensional Arrays 1 2 3 4 5 6 7 8 9 10 1 2 3 4 x 11 Declaration: int matrix[4][11]; columns rows

Element Access Access the j-th element (column) of the i-th array (row) matrix[i][j] column row

Initializing Two-dimensional Arrays int arr[2][3] = { {1, 2, 3}, {4, 5, 6} }; As with regular array size can be inferred from initialization. Unlike regular array, this is only true for the number of rows (first dimension) int arr[][3] = { {1, 2, 3}, {4, 5, 6} }; 1 2 3 4 5 6

Example: Matrix Addition #define ROWS 3 #define COLS 4 int main() { int a[ROWS][COLS] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}; int b[ROWS][COLS] = {{1,1,1,1},{2,2,2,2},{3,3,3,3}}; int c[ROWS][COLS]; int i = 0, j = 0; for (i = 0; i < ROWS; ++i) for (j = 0; j < COLS; ++j) c[i][j] = a[i][j] + b[i][j]; /* print c */ ... return 0; }

Exercise Write a program that: defines three int matrices: a,b and c of size 3x3 initialize a and b with any values you want. compute the matrix multiplication of a and b: a*b, and store it in c Print c

SOLVE A MAZE Our maze is represented by a rectangle divided into small squares = a matrix It has: Starting point End point Walls Empty cells that we can travel through

SOLVE A MAZE How do we solve a maze? Go in an arbitrary direction path until we Reach the End  DONE Hit a wall  reverse to find a new possible direction  RECURSION

SOLVE A MAZE S When hitting a cell that is already in the path: E Reverse to avoid infinite loop

SOLVE A MAZE Algorithm: When you reach a cell: Try walking down / right / up / left in some order until: Success = Reach END Failure = Checked all possible paths

SOLVE A MAZE Reverse when you hit: The function solve receives: A Wall A border A cell in the path A cell that was visited bus is not in the path The function solve receives: - maze (2d matrix) - (row, col) of current cell - step (cell num on the path)

int solve(int maze[][WIDTH], int h, int w, int step) { // check borders if ( (h < 0) || (h >= HEIGHT) || (w < 0) || (w >= WIDTH) ) return FALSE; switch (maze[h][w]) case END: return TRUE; case EMPTY: maze[h][w] = step; // the actual walk along the path if (solve(maze, h + 1, w, step + 1) || solve(maze, h, w + 1, step + 1) || solve(maze, h - 1, w, step + 1) || solve(maze, h, w - 1, step + 1)) maze[h][w] = VISITED; // Failed default: // PATH or VISITED or failed EMPTY }

SOLVE A MAZE – Main int main() { int maze[HEIGHT][WIDTH] = {EMPTY}; init_maze(maze); print_maze(maze); if (solve(maze, 0, 0, 1)) printf("Solution:\n"); } else printf("No solution\n"); return 0;

Eight Queens Puzzle Place eight chess queens on an 8×8 chessboard so that no two queens attack each other. A solution requires that no two queens share the same row, column, or diagonal.

Eight Queens Puzzle

Eight Queens Puzzle The eight queens puzzle has 92 distinct solutions. 12 unique solutions, when uniting solutions that differ only by symmetry operations (rotations and reflections).

Eight Queens Puzzle Searching for a solution - Insights: There is exactly one queen in each row. Thus, in each step place a queen in the next row that does not contain a queen. In the next row - consider only the columns that are not already attacked by another queen.

Eight Queens Puzzle – Take 1 #define SIZE 8 #define EMPTY 0 #define QUEEN 1 int main() { int board[SIZE][SIZE] = {EMPTY}; if (solve(board)) print_board(board); else printf("Failed to solve the %d queens problem\n"); return 0; }

Eight Queens Puzzle – Take 1 int solve(int board[][SIZE) { int row, col; for (row = 0; row < SIZE; ++row) for (col = 0; col < SIZE; ++col) if (check(board, row, col)) board[row][col] = QUEEN; } if (col == SIZE) return FALSE; return TRUE;

Eight Queens Puzzle – Take 1 // helper - returns FALSE if a QUEEN is found on a path // Prevents code duplication in check int helper(int board[][SIZE], int row, int col, int add_row, int add_col) { int i, j; i = row + add_row; j = col + add_col; while ((i >= 0) && (i < SIZE) && (j >= 0) && (j < SIZE)) if (board[i][j] == QUEEN) return FALSE; i += add_row; j += add_col; } return TRUE;

Eight Queens Puzzle – Take 1 int check(int board[][SIZE], int row, int col) { return // check column (helper(board, row, col, 1, 0) && helper(board, row, col, -1, 0) && // check row helper(board, row, col, 0, 1) && helper(board, row, col, 0, -1) && // check diagonal helper(board, row, col, 1, 1) && helper(board, row, col, 1, -1) && // check other diagonal helper(board, row, col, -1, 1) &&helper(board, row, col, -1, -1)); }

Eight Queens Puzzle – Problem After adding 5 queens we get:

Eight Queens Puzzle – Solution Add Recursion! When there is no solution, return to the last added Queen and move her to the next possible cell. If no such cell exists – move one Queen up. Change solve to be recursive. Now solve receives the board and the row number.

Eight Queens Puzzle – Solution int solve(int board[][SIZE], int row) { int col; if (row == SIZE) return TRUE; for (col = 0; col < SIZE; ++col) if (check(board, row, col)) board[row][col] = QUEEN; if (solve(board, row + 1)) return TRUE; // else - reset last assignment, try next possible column board[row][col] = EMPTY; } return FALSE;