Find a number inside a matrix

조회 수: 49(최근 30일)
jean claude
jean claude 2020년 10월 28일
편집: Jon 2020년 10월 30일
  댓글 수: 2
jean claude
jean claude 2020년 10월 28일
exactly you're right ! basically it's a python question since i am not that good in python i tried to solve it by matlab first after that convert to python, what do you think ?

댓글을 달려면 로그인하십시오.

답변(1개)

Jon
Jon 2020년 10월 28일
There are probably more efficient ways to do this but one approach would be to utilize MATLAB's find function.
If your matrix were given by A you can find for example the locations of all of the 8's using
[mIdx,nIdx] = find(A == 8)
Note this returns a vector, mIdx of row indices and vector nIdx of column indices where the 8's are located.
You could then find all of the 2's using
[pIdx, qIdx] = find( A == 2)
you could then check for each pair indices whether they were adjacent (within 1 element of each other)
if so add it to the list and so on
  댓글 수: 2
Jon
Jon 2020년 10월 30일
3 days in your room is too long :)
I think one approach would be to think of this as a recursive graph traversal where you are trying to find the whole sequence. Your search starts on one of the 8's. You look 1 column to the left. Is it a 2? If it it is then move to that 2, if not then look 1 row above etc until you either find an adjacent 2 or you eliminate that 8 as being isolated. Once you move to the 2 then you similarly look for adjacent 9's. If you find one then move to that 9 add it to the list of traversed nodes so far and start looking for an adjacent 2. When you hit a dead end back up. Continue in this manner until you either reach your final digit or have hit a dead end. I would suggest first doing it by hand (with a pencil and a sheet of paper) working through how you do it. Then see if you can implement it. I'm thinking you'd use the find command just to find all of the 8's which would be the starting points for your search. Then you'd dive into each one with your recursive search. In your recursive function you will need to keep track of the digits you've found so far and the last location you came from so you can go back. You also need a condition that sends you back up, either you've hit a dead end or you've found your final digit. If you aren't familiar with doing these kind of graph searches look for example at how people do depth first search of a graph to get some ideas.

댓글을 달려면 로그인하십시오.

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by